Exception Handling
Exception Handling
Introduction
• Exception handling
– Catch errors before they occur
– Deals with synchronous errors (i.e., divide by zero)
– Does not deal with asynchronous errors
• Disk I/O completions, mouse clicks - use interrupt processing
– Used when system can recover from error
• Exception handler - recovery procedure
• Error dealt with in different place than where it occurred
– Useful when program cannot recover but must shut down
cleanly
Introduction
• Exception handling
– Should not be used for program control
• Not optimized, can harm program performance
– Improves fault-tolerance
• Easier to write error-processing code
• Specify what type of exceptions are to be caught
– Another way to return control from a function or block of
code
When Exception Handling Should
Be Used
• Error handling used for
– Processing exceptional situations
– Processing exceptions for components that cannot handle
them directly
– Processing exceptions for widely used components
(libraries, classes, methods) that should not process their
own exceptions
– Large projects that require uniform error processing
The Basics of Java Exception Handling
• Exception handling
– Method detects error which it cannot deal with
• Throws an exception
– Exception handler
• Code to catch exception and handle it
– Exception only caught if handler exists
• If exception not caught, block terminates
The Basics of Java Exception Handling
• Format
– Enclose code that may have an error in try block
– Follow with one or more catch blocks
• Each catch block has an exception handler
– If exception occurs and matches parameter in catch block
• Code in catch block executed
– If no exception thrown
• Exception handling code skipped
• Control resumes after catch blocks
try{
code that may throw exceptions
}
catch (ExceptionType ref) {
exception handling code
}
The Basics of Java Exception Handling
Program Output
Program Output
Try Blocks
• throw
– Indicates exception has occurred (throwing an exception)
– Operand
• Object of any class derived from Throwable
95 if ( denominator == 0 )
96 throw new DivideByZeroException();
• Exceptions
– Can still throw exceptions without explicit throw statement
• ArrayIndexOutOfBoundsException
– Terminates block that threw exception
Catching an Exception
• catch blocks
– Contain exception handlers
– Format:
catch( ExceptionType ref ) {
error handling code
}
• Catching exceptions
– First handler to catch exception does
• All other handlers skipped
– If exception not caught
• Searches enclosing try blocks for appropriate handler
try{
try{
throw Exception2
}
catch ( Exception1 ){...}
}
catch( Exception2 ){...}
• Information
– Information can be passed in the thrown object
• If a catch block throws an exception
– Exception must be processed in the outer try block
• Usage of exception handlers
– Rethrow exception (next section)
• Convert exception to different type
– Perform recovery and resume execution
– Look at situation, fix error, and call method that generated
exception
– Return a status variable to environment
Rethrowing an Exception
• Rethrowing exceptions
– Use if catch handler cannot process exception
– Rethrow exception with the statement:
throw e;
• Detected by next enclosing try block
– Handler can always rethrow exception, even if it performed
some processing
Throws Clause
• Throws clause
– Lists exceptions that can be thrown by a method
int g( float h ) throws a, b, c
{
// method body
}
• Run-time exceptions
– Derive from RunTimeException
– Some exceptions can occur at any point
• ArrayIndexOutOfBoundsException
• NullPointerException
– Create object reference without attaching object to
reference
• ClassCastException
– Invalid casts
– Most avoidable by writing proper code
Throws Clause
• Checked exceptions
– Must be listed in throws clause of method
– All non-RuntimeExceptions
• Unchecked exceptions
– Can be thrown from almost any method
• Tedious to write throws clause every time
• No throws clause needed
– Errors and RunTimeExceptions
Throws Clause
• Catch-or-declare requirement
– If method calls another method that explicitly throws
checked exceptions
• Exceptions must be in original method's throws clause
– Otherwise, original method must catch exception
– Method must either catch exception or declare it in the
throws clause
Exceptions and Inheritance
• Inheritance
– Exception classes can have a common superclass
– catch ( Superclass ref )
• Catches subclasses
• "Is a" relationship
– To catch all exceptions, catch an exception object:
catch( Exception e )
– Polymorphic processing
– Easier to catch superclass than catching every subclass
finally Block
• Resource leaks
– Programs obtain and do not return resources
– Automatic garbage collection avoids most memory leaks
• Other leaks can still occur
• finally block
– Placed after last catch block
– Can be used to returns resources allocated in try block
– Always executed, irregardless whether exceptions thrown or
caught
– If exception thrown in finally block, processed by
enclosing try block
1 // Fig. 14.9: UsingExceptions.java
2 // Demonstration of stack unwinding.
3 public class UsingExceptions {
4 public static void main( String args[] )
5 { 1. main
6 try { Call method throwException
7 throwException(); (enclosed in a try block).
8 } 1.1 throwException
9 catch ( Exception e ) {
10 System.err.println( "Exception handled in Throw Exception.
main"an); The catch block
1.2 catch
11 } cannot handle it, but the finally block
12 } executes irregardless.
13 2. Define
14 public static void throwException() throws Exception throwException
15 {
16 // Throw an exception and catch it in main.
17 try { 2.1 try
18 System.out.println( "Method throwException" );
19 throw new Exception(); // generate exception
20 }
2.2 catch
21 catch( RuntimeException e ) { // nothing caught here
22 System.err.println( "Exception handled in " + 2.3 finally
23 "method throwException" );
24 }
25 finally {
26 System.err.println( "Finally is always executed" );
27 }
28 }
29 }
Method throwException
Finally is always executed
Exception handled in main Program Output
Using printStackTrace and
getMessage
• Class Throwable
– Superclass of all exceptions
– Offers method printStackTrace
• Prints method call stack for caught Exception object
– Most recent method on top of stack
• Helpful for testing/debugging
– Constructors
• Exception()
• Exception( String informationString )
– informationString may be accessed with method
getMessage
1 // Fig. 14.10: UsingExceptions.java
2 // Demonstrating the getMessage and printStackTrace
3 // methods inherited into all exception classes.
4 public class UsingExceptions {
5 public static void main( String args[] )
6 {
1. main
Call method1, which calls
7 try { method2, which calls method3,
8 method1(); 1.1 try
which throws an exception.
9 }
10 catch ( Exception e ) {
11 System.err.println( e.getMessage() + "\n" ); 1.2 getMessage
12
13 e.printStackTrace();
14 }
getMessage prints the 1.3
String the
printStackTrace
15 } Exception was initialized with.
16
17 public static void method1() throws Exception 2. method1
18 {
19 method2(); printStackTrace prints the methods in this
20 } order: 3. method2
21
22
method3
public static void method2() throws Exception
method2 4. method3
23 {
24 method3(); method1
25 } main 4.1 throw
26
27 public static void method3() throws (order they were called
Exception when exception occurred)
28 {
29 throw new Exception( "Exception thrown in method3" );
30 }
31 }
Exception thrown in method3
java.lang.Exception: Exception thrown in method3
at UsingExceptions.method3(UsingExceptions.java:28)
at UsingExceptions.method2(UsingExceptions.java:23)
Program Output
at UsingExceptions.method1(UsingExceptions.java:18)
at UsingExceptions.main(UsingExceptions.java:8)