Exception Handling Yaodong Bi bics uofs edu Exception
Exception Handling Yaodong Bi bi@cs. uofs. edu
Exception Handling l l l l l Java exception handling Try blocks Throwing and re-throwing an exception Catching an exception Throws clause Exceptions in constructors and finalizers Exception and inheritance The finally block Print. Stack. Trace() and get. Message()
Java Exception Handling l l l To process only exceptional situations where a method is unable to complete the task for reasons it cannot control To process exceptions from program components that are not geared to handling those exceptions directly To process exceptions from components such as libraries and classes that are likely to be widely used and where those components cannot handle their own exceptions
Java Exception Handling l l l When an exception does not occur, little or no overhead is imposed by the presence of exception handling code. When exceptions occur, they do incur execution-time overhead Use Java’s standardized exception handling to improve program clarity and fault tolerance
Exception Handling Basics l l l When a block of code (ex. , a method) detects an error it cannot handle, it throws an exception The programmer encloses in a try block the code that may throw an exception. The try block is immediately followed by zero or more catch blocks to catch the exception(s) Each catch block specifies the type of exception it can catch and contains an exception handler An optional finally block (mandatory when no catch clause provided) will be executed regardless of whether or not there is an exception.
Exception Handling Basic l l A method can use a throws clause to specify what exceptions it may throw Java employs the termination model of exception handling. – Once an exception is thrown, the block in which the exception is thrown terminates and control cannot return to the throw point
Ex. 1: Divide By Zero public class Exception. Handling { public static int quotient(int numerator, int denominator) throws Divide. By. Zero. Exception { if (denominator == 0) throw new Divide. By. Zero. Exception(); return numerator / denominator; } public static void main(String[] arg) { try { quotient(100, 0); } catch (Divide. By. Zero. Exception e) { System. err. println(e. to. String()); }
Ex. 1: Divide By Zero } finally { System. out. println("Finally Block"); } } // the following is saved in a separate file public class Divide. By. Zero. Exception extends Arithmetic. Exception { public Divide. By. Zero. Exception() { super("Divide by Zero"); } public Divide. By. Zero. Exception(String s) { super(s); } }
Try blocks try { // code that may throw exceptions } catch (Exception. Type ref) { // exception handler } l l l A try block can be followed by zero or more catch blocks If the try block executes with no exception thrown, all the exception handlers are skipped and control resumes with the first statement after the last exception handler If a finally block follows the last catch block, it will be executed regardless of whether or not an exception is thrown
Throwing Exceptions l The throw statement makes an exception to occur – throwing an exception – l l l throw new Divide. By. Zero. Exception(); A throw statement must throw an object of any class derived from class Throwable When an exception is thrown, control exits the current try block and proceeds to an appropriate catch handler When to. String() is invoked on any Throwable object, it returns the String that was supplied to the constructor public class Divide. By. Zero. Exception extends Arithmetic. Exception { public Divide. By. Zero. Exception() { super("Divide by Zero"); // return by to. String() }
Catching Exceptions l l Each catch block starts with the keyword catch followed by parentheses containing a class name (type of exception) The Exception object caught can be referred through the parameter catch (Exception. Type ref) { // using ref to refer to the exception object } l It is possible that several handlers provide an acceptable match to the type of the exception, the first exception handler that matches the exception type is executed.
Catching Exceptions l l l Each catch block defines a distinct scope An exception handler cannot access objects defined in other handlers Objects defined in a try block cannot be accessed in its exception handlers try { int try. X = 100; … } catch (Exception. Type 1 ref) { int catch 1 Y = 200; // try. X is NOT accessible here } catch (Exception. Type 2 ref) { // both try. X and catch 1 Y are NOT accessible here }
Catching Exceptions l Exceptions thrown from a handler cannot be caught by the catch blocks of the current try-catch structure 1 try { 2 try { throw new Exc. Type 1(); } 3 catch (Exc. Type 1 ref) 4 { 5 throw new Exc. Type 2(); 6 } 7 catch (Exc. Type 2 ref) 8 { 9 // this will NOT catch the Exc. Type 2 thrown from line 5 10 } 11 catch (Exc. Type 2 ref) 12 { 13 // catch the Exc. Type 2 exception thrown from line 5 14 }
Re-throwing Exceptions l l When a exception handler cannot or does not want to handle the caught exception completely, it can re-throw the exception using the throw statement. Such a re-thrown exception is handled by the enclosing try-catch block 1 try { 2 try { throw new Exc. Type 1(); } 3 catch (Exc. Type 1 ref) 4 { 5 throw ref; 6 } 7 catch (Exc. Type 1 ref) 8 { 9 // catch the Exc. Type 1 exception thrown from line 5 10 }
Throws Clause l A throws clause lists the exceptions that can be thrown by a method void foo() throws Exception. A, Exception. B Exception. A { // may throw the above three exceptions } l l All exceptions must be handled exception Error and Runtime. Exception If a method does not handle exceptions that may be thrown from its body, it must use throws clause for the caller to handle the exceptions public void add. Course(String cid, String ttl) throws SQLException { … st. execute. Update(sql); // may throw SQLException }
Java Exception Hierarchy Object Throwable Error Linkage. Error Exception AWTError Runtime. Exception Class. Not. Found. Exception No. Such. Method. Exception Must be handled Arithmetic. Exception Array. Store. Exception
Java Exception Hierarchy l l You can throw only objects that derive from the Throwable class. Errors: – – l When a "hard" failure in the virtual machine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors and it's unlikely that typical Java programs will ever throw Errors either. Exceptions: – – Most programs throw and catch objects that derive from the Exception class. Exception has a special subclass Runtime. Exception which is not required to be handled
Runtime Exceptions l The Runtime. Exception class represents exceptions that occur within the Java virtual machine (during runtime). – l l An example of a runtime exception is Null. Pointer. Exception. The Java packages define several Runtime. Exception classes. You can catch these exceptions just like other exceptions. A method is not required to specify that it throws Runtime. Exceptions. The cost of checking for all Runtime. Exceptions often outweighs the benefit of catching it. the compiler allows Runtime. Exceptions to go uncaught and unspecified.
Exception and Inheritance l If a catch is written to catch exception objects of a superclass type, it can also catch all objects of subclasses of that superclass – l l catch (Exception e) { } would catch almost all exceptions This also allows for polymorphic processing of related exceptions It is a syntax error if a catch that catches a superclass object is placed before a catch that catches an object of a subclass of that superclass
The finally Block l l The finally block is optional; if it present it must be placed after the last catch block The finally block can be used to control resource leaks try { // may throw exceptions } catch (Exception. Type 1 ref) { // exception handling statements } catch (Exception. Type 2 ref) { // exception handling statements } finally { // statements // resource release statements }
The finally Block l A finally block will be executed (if present) regardless of whether or not any exception is thrown and regardless of whether the exception is handled or not. – – If there is no exception, it will be executed after the try block If there is an exception and it is handled by a handler, it will be executed after the catch is completed If there is an exception and it is not handled by a catch, it will be executed after the termination of the try block and then the exception is passed to to next level If there is an exception in a catch block, it will be executed after the catch block terminates and then the exception is passed to next level
print. Stack. Trace() and get. Message() l l l Class Throwable offers a print. Stack. Trace method that prints the method call stack Class Exception inherits the method Two constuctors for Exception public Exception() //accept no parameter public Exception(String str) // accept a string – The str stored in Exception may be queried with method get. Message()
print. Stack. Trace & get. Message() public class Exception. Handling { public static int quotient(int numerator, int denominator) throws Divide. By. Zero. Exception { if (denominator == 0) throw new Divide. By. Zero. Exception(); return numerator / denominator; } public static void main(String[] arg) { try { quotient(100, 0); } catch (Divide. By. Zero. Exception e) { System. err. println(e. get. Message()); e. print. Stack. Trace(); } } }
print. Stack. Trace & get. Message() l The following will be printed by the program – Printed by Divide by Zero get. Message() – Printed by print. Stack. Trace() Divide. By. Zero. Exception: Divide by Zero at Exception. Handling. quotient(Exception. Handling. java: 7) at Exception. Handling. main(Exception. Handling. java: 15)
- Slides: 24