Main mechanism for handling exceptional errors try { // statements that could raise an exception // or a method call that could raise an exception } catch (exception_class exception_object) { // statements to handle the exception // or rethrow the exception // specific type (subclass) of exception } catch (exception_class exception_object) { // ... // more general (superclass) exception type } // end try
3
14.2 – Exception Handling Overview
4
Application Deconstructed package inclass.Exceptions; import java.util.Scanner; public class DivideByZero { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter two integers: "); int num = keyboard.nextInt(); int den = keyboard.nextInt(); try { System.out.println("Quotient = " + num / den); } catch (ArithmeticException ae) { System.out.println(ae.getMessage()); } // end try } // end main() Enter two integers: 2 0 } // end DivideByZero / by zero 5
14.3 – Exception Handling Advantages
6
Application Deconstructed package inclass.Exceptions; import java.util.Scanner; public class DivideByZeroMethod { public static int quotient(int numerator, int denominator) { if (denominator == 0) throw new ArithmeticException("Denominator cannot be 0"); else return numerator / denominator; } // end quotient()
7
Application Deconstructed public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter two integers: "); int num = keyboard.nextInt(); int den = keyboard.nextInt(); try { System.out.println("Quotient = quotient(num, den); } catch (ArithmeticException ae) { System.out.println(ae.getMessage()); } // end try } // end main() } // end DivisionByZeroMethod Enter two integers: 2 0 Denominator cannot be 0
8
14.4 – Exception Types
9
Exceptions come in two flavors: Checked and Unchecked Object Throwable Exception
method2() throws Exception { if (error occurs) { throw new Exception(); }
}
Throw exception
Catch exception }
12
Checked exceptions must be either a) caught or b) declared. In method1(), the exception is caught locally but in method2() it is instead thrown. By throwing the exception you are indicating that some other method higher in the calling order is to handle this error. The compiler however needs to know that there is a possibility for such an error to occur, and so you must indicate so by declaring the exception in the method header.
Exception objects can provide valuable information
Application Deconstructed package inclass.Exceptions; import java.util.Scanner; public class DivideByZero { public static void main(String[] args) { // Code omitted ... try { System.out.println("Quotient = " + num / den); } catch (ArithmeticException ae) { System.out.println("getMessage(): " + ae.getMessage()); System.out.println("toString(): " + ae); System.out.println("printStackTrace(): "); ae.printStackTrace(); } // end try } // end main() } // end DivideByZero
14
Application Deconstructed Enter two integers: 2 0 getMessage(): / by zero toString(): java.lang.ArithmeticException: / by zero printStackTrace(): java.lang.ArithmeticException: / by zero
at inclass.Exceptions.DivideByZero.main(DivideByZero.java:14) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at edu.rice.cs.dynamicjava.symbol.JavaClass$JavaMethod.evaluate(JavaClass.java:362) at edu.rice.cs.dynamicjava.interpreter.ExpressionEvaluator.handleMethodCall(ExpressionEvaluator.java:92) // output omitted
15
14.6 – The finally Clause
16
Do necessary clean-up in the finally block try { // statements that could raise an exception // or a method call that could raise an exception } catch (exception_class exception_object) { // statements to handle the exception // or rethrow the exception // specific type (subclass) of exception } catch (exception_class exception_object) { // ... // more general (superclass) exception type } finally { // clean up } // end try
17
The finally clause is used as a always-execute clause. It executes no matter what happens with the catch clauses. In other words, if an error is caught the finally executes, and if an error does not occur, well the finally still executes. This provides you the opportunity to do tasks that need to happen no matter what, like releasing resources.
Application Deconstructed package inclass.Exceptions; import java.io.*; public class FinallyDemo { public static void main(String[] args) { PrintWriter pw = null; try { pw = new PrintWriter("text.txt"); pw.println("Welcome to java."); } catch (IOException e) { e.printStackTrace(); } finally { if (pw != null) pw.close(); } // end try } // end main() } // end FinallyDemo 18
14.7 – When to use Exceptions
19
Follow these guidelines ! Catch error locally ! Handle error in caller ! Use simple if logic with a boolean return when possible ! Use try/catch for exceptional errors
20
14.8 – Rethrowing Exceptions
21
An exception can be rethrown try { statements; } catch (AnException e) { performs tasks before it exits; throw e; } // end try
22
14.9 – Chained Exceptions
23
Exceptions can also be chained try { method(); } catch (AnException e) { // performs tasks before it exits throw new AnException("More info", e); } // end try method() throws AnException { throw new AnException("Old info"); } // end method()
24
method() throws an exception with the message "Old info". This object is then caught by the catch clause and a new exception object is thrown. This new object contains the cumulative message from both methods. The message "More info" followed by the message "Old info"
Application Deconstructed package inclass.Exceptions; public class ChainedExceptionsDemo { public static void main(String[] args) { try { method1(); } catch (Exception e) { e.printStackTrace(); } // end try } // end main()
25
Application Deconstructed < ChainedExceptionsDemo.java > public static void method1() throws Exception { try { method2(); } catch (Exception e) { throw new Exception("New info from method1", e); } // end try } // end method1() public static void method2() throws Exception { throw new Exception("New info from method2"); } // end method2() } // end ChainedExceptionsDemo
26
Application Deconstructed < ChainedExceptionsDemo.java > java.lang.Exception: New info from method1 at inclass.Exceptions.ChainedExceptionsDemo.method1(ChainedExceptionsDemo.java:16) at inclass.Exceptions.ChainedExceptionsDemo.main(ChainedExceptionsDemo.java:6) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ... more Caused by: java.lang.Exception: New info from method2 at inclass.Exceptions.ChainedExceptionsDemo.method2(ChainedExceptionsDemo.java:21) at inclass.Exceptions.ChainedExceptionsDemo.method1(ChainedExceptionsDemo.java:14) ... 38 more
27
The error messages are chained in a Stack fashion. The first message generated is at the bottom of the stack and the last one on the top.
14.10 – Creating Custom Exception Classes
28
You could always create your own exception class
29
Application Deconstructed package testing; public class ArgumentException extends Exception { private int value; public ArgumentException(int value) { super(value + " is out of range."); this.value = value; } // end ArgumentException() public String toString() { return (value + " is out of range."); } // end toString() } // end ArgumentException
30
Application Deconstructed package testing; public class ArgumentExceptionDemo { public static void main(String[] args) { try { throw new ArgumentException(-1); } catch (ArgumentException ae) { System.err.println(ae); } // end try } // end main() } // ArgumentExceptionDemo
-1 out of range
31
Recap: Exceptions Use a try / catch block to handle exceptions Pair a try with either a catch or finally block Trap locally, handle in caller (or above) Declare or catch checked exceptions 32