0% found this document useful (0 votes)
13 views21 pages

OOP Chapter 5 - Exception Handling

Chapter Five discusses exception handling in programming, defining exceptions as objects that indicate unusual situations that can disrupt program flow. It differentiates between checked and unchecked exceptions, providing examples and explaining how to handle them using try-catch blocks. The chapter also covers the use of keywords like 'throw', 'throws', and the process of creating custom exceptions.

Uploaded by

samih4376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views21 pages

OOP Chapter 5 - Exception Handling

Chapter Five discusses exception handling in programming, defining exceptions as objects that indicate unusual situations that can disrupt program flow. It differentiates between checked and unchecked exceptions, providing examples and explaining how to handle them using try-catch blocks. The chapter also covers the use of keywords like 'throw', 'throws', and the process of creating custom exceptions.

Uploaded by

samih4376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Chapter Five

Exceptions Handling

7/7/2024 1
Exceptions
◼ An exception is an object that describes an unusual or
erroneous situation
◼ Exceptions are thrown by a program, and may be caught and
handled by another part of the program

7/7/2024 2
Exception Hierarchy
◼ Errors:
◼ Errors are fairly rare and usually fatal. They are caused by bugs
in the Java VM, or by the program running out of memory or
other resources.
◼ Errors are usually not handled by programs.
◼ Exceptions:
◼ Exceptions can be caused by bugs in the program or improper
data supplied to the program
◼ Exceptions should be handled, or caught
◼ An exception is either checked or unchecked
◼ Checked exceptions must be caught or declared as thrown.
◼ You are not required to handle unchecked exceptions.

7/7/2024 3
Attack of the Exception
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

◼ What happens when this method is used to take the average of


an array of length zero?
◼ Program throws an Exception and fails
java.lang.ArithmeticException: / by zero

7/7/2024 4
What is an Exception?
◼ An error event that disrupts the program flow and may
cause a program to fail.
◼ Some examples:
◼ Performing illegal arithmetic
◼ Illegal arguments to methods
◼ Accessing an out-of-bounds array element
◼ Hardware failures
◼ Writing to a read-only file

7/7/2024 5
Another Exception Example
◼ What is the output of this program?
public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}

Output:
Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)

7/7/2024 6
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)

◼ What exception class? ArrayIndexOutOfBoundsException


◼ Which array index is out of bounds? 2
◼ What method throws the exception? main
◼ What file contains the method? ExceptionExample.java
◼ What line of the file throws the exception? 4

7/7/2024 7
Classifying Java Exceptions
◼ Unchecked Exceptions
◼ All the exceptions we've seen so far have been Unchecked
Exceptions, or Runtime Exceptions
◼ Usually occur because of programming errors, when code is
not robust enough to prevent them
◼ They are numerous and can be ignored by the programmer
◼ Common Unchecked Exceptions
◼ NullPointerException: reference is null and should not be
◼ IllegalArgumentException: method argument is improper in
some way
◼ ArrayIndexOutOfBouncdsException: Accessing an out-of-
bounds array element

7/7/2024 8
◼ Checked Exceptions
◼ Usually occur because of errors programmer cannot control
◼ examples: hardware failures, unreadable files
◼ They are less frequent and they cannot be ignored by the
programmer . . .
◼ Every method must catch (handle) checked exceptions or
specify that it may throw them
◼ Specify with the throws keyword

7/7/2024 9
Checked and Unchecked Exceptions
Checked Exception Unchecked Exception

not subclass of RuntimeException subclass of RuntimeException


if not caught, method must specify if not caught, method may specify it to
it to be thrown be thrown
for errors that the programmer for errors that the programmer can
cannot directly prevent from directly prevent from occurring,
occurring
IOException, NullPointerException,
FileNotFoundException, IllegalArgumentException,
SocketException ArrayIndexOutOfBoundsException

7/7/2024 10
Exception Class Hierarchy
◼ All exceptions are instances of classes that are subclasses
of Exception
Exception

RuntimeException IOException SQLException

ArrayIndexOutofBounds FileNotFoundException

NullPointerException MalformedURLException

IllegalArgumentException SocketException

etc. etc.

Unchecked Exceptions Checked Exceptions

7/7/2024 11
Keywords for Java Exceptions
◼ throws: - is a keyword used in the method signature used to
declare an exception which might get thrown by the function
while executing the code.
◼ throw: - is a keyword which is used to throw an exception
explicitly in the program inside a function or inside a block
of code.
◼ try: - Marks the start of a block associated with a set of
exception handlers.
◼ catch: - If the block enclosed by the try generates an
exception of this type, control moves here; watch out for
implicit subsumption.
◼ finally: - Always called when the try block concludes, and
after any necessary catch handler is complete.
7/7/2024 12
Exceptions Terminology
◼ When an exception happens we say it was thrown or
raised
◼ When an exception is dealt with, we say the exception is
handled or caught

7/7/2024 13
Exception Handling
◼ Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}

7/7/2024 14
Exception Handling Example
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

public static void printAverage(int[] a) {


try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
}
7/7/2024 15
Catching Multiple Exceptions
◼ Handle multiple possible exceptions by multiple successive
catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}

7/7/2024 16
Exception Constructors
◼ Exceptions have at least two constructors:
1. no arguments
NullPointerException e = new NullPointerException();
2. single String argument descriptive message that appears when
exception error message is printed
IllegalArgumentExceptione e =
new IllegalArgumentException("number must be positive");

7/7/2024 17
Writing Your Own Exception
◼ To write your own exception, write a subclass of Exception
and write both types of constructors
public class MyCheckedException extends IOException {
public MyCheckedException() {}
public MyCheckedException(String m) {
super(m);
}
}
public class MyUncheckedException extends RuntimeException {
public MyUncheckedException() {}
public MyUncheckedException(String m) {
super(m);
}
}

7/7/2024 18
Throwing Exceptions
◼ Throw exception with the throw keyword
public static int average(int[] a) {
if (a.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

7/7/2024 19
Throw Statement and Throws Clause
public class JavaTester{
public int division(int a, int b) throws ArithmeticException{
int t = a/b;
return t;
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
try{
System.out.println(obj.division(15,0));
}catch(ArithmeticException e){
System.out.println("You shouldn't divide number by zero");
}
}
}

7/7/2024 20
Throws and Inheritance
◼ A method can throw less exceptions, but not more, than the
method it is overriding
public class MyClass {
public void doSomething() throws IOException, SQLException {
// do something here
}
}

public class MySubclass extends MyClass {


public void doSomething() throws IOException {
// do something here
}
}

7/7/2024 21

You might also like