10. Exception Handling
10. Exception Handling
10. Exception Handling
Exception Handling
1. Exceptions
Exception
Event that occurs in the execution of a prog and breaks the expected flow of
the prog if it is not handled.
Disadvantages
Exception mechanism allows focusing on writing code for the main thread
and then handling exception in another place
readFile(){
try{
//open the file
//determine its size
//allocate that much mem
// read the file into mem
//close the file
} catch(fileOpenFailed){
// do smth
} catch(sizeDeterminationFailed){
// do smth
} catch(memoryAllocationFailed){
// do smnth
} catch(readFailed){
//do smth
} catch(fileCloseFailed){
//do smth
}
}
OO approach
All the exceptions are representations of a class derived from the class
Throwable (or its child classes).
These objs must send the info of exceptions (type and prog status) from the
place that exception occured to where they are controlled/handled.
Try/catch block
try{
//code block that might cause exception
} catch(ExceptionType e){ // descendant of Throwable
// handling exception
}
IOException
import java.io.InputStreamReader;
import java.io.IOException;
Nested try/catch
try{
// may cause exception type 1
try{
// may cause exception type 2
} catch(ExceptionType2){
// handle exception type 2
}
} catch(ExceptionType1){
// handle exception type 1
}
try{
// may cause multiple exception
} catch(ExceptionType1 e1){
//handle exc type 1
} catch(ExceptionType2 e2){
//handle exc type 2
}
Warning
Example
public static void main( String args[]) {
try {
// format a number
// read a file
// something else...
} catch(IOException e) {
System.out.println("I/O error "+e.getMessage();
} catch(NumberFormatException e) {
System.out.println("Bad data "+e.getMessage();
} catch(Throwable e) { // catch all
System.out.println("error: " + e.getMessage();
}
}
finally block
Ensure that every necessary tasks are done when an exception occurs
Closing file, closing socket, connection
Releasing resource (if necessary)
Must be done even there is an exception occurring or not
try{
// code block that can have exceptions
} catch(Exception e){
//handle exception
} finally{
// task for all cases, whether exceptions are raised or not
}
Handle it immediately
Delegate to its caller if don't want to handle immediately, by using throw
and throws
Warning
Lan 13
java.lang.ArithmeticException: Cannot divide by 0.
at Demo.cal(Demo.java:16)
at Demo.main(Demo.java:8)
Note
When overriding a method of a parent class, methods in its child classes can
not throw any new exception but only a set of exceptions that are a subset
of exceptions thrown from the parent class (or similar to).
Easy to use
Separate exception handling from the main code
Throw automatically, do not miss any exception
Group and categorize exceptions
Make prog easier to read and more reliable
4. User-defined exceptions
why do we need user-defined exceptions ?