Exception Handling Part 1: Handing Java Exceptions CSIS 3701: Advanced Object Oriented Programming
What is an Exception? Error: Fault in program that causes it to incorrectly implement abstract concept –Example: pop method that does not remove value from stack Exception: Situation where abstract concept undefined –Example: popping from empty stack Often caused by user error
Examples of Exceptions Abstract conceptException Division0 / 0 Square root sqrt(x) Negative numbers Array access A[index]index outside bounds of array Reference access object.method() object is null Problem: Must still somehow handle these problems if they occur in program!
Handling Exceptions What are options for handling exceptions? –Ignore problem (array out of bounds in C) –Shut down program (null pointer in C) –Print message… What is best option? –Bank software Save data, shut down, report error –Autopilot software Display alert, but keep running! No universal best way to handle exception Only user of class can decide how to handle!
Detecting/Handling Exceptions Call that causes exception s.pop(); Code to handle exception User code Code to detect exception public int pop(){ if (top == 0) Must signal exception to user Class code call signal
Signaling Exceptions How can your code signal user about exception? Return a value (such as true/false)? –User can ignore signal (like any other return value) –Method may already be returning a value pop() cannot return true/false, as must return an int Must signal exception without returning a value –Code throws an exception object to caller –Caller catches exception object and handles problem in whatever way considered appropriate
Throwing/Catching Exceptions try { call that might cause exception … } catch(ExceptionType e) { code to handle exception } User code method(…) { code to detect exception throw new ExceptionType(); } Class code Exception object thrown back to caller
Exception Handling Syntax … try { Call that may cause exception Any other code that should not be called if exception occurs } catch(ExceptionType e) { code to handle this type of exception } code after exception handing If exception is thrown, skip to corresponding catch and execute its code Then skip to first code after try/ catch block If no exception is thrown by end of try block, skip catch blocks
Multiple Exceptions … try { Call that may cause exception Any other code that should not be called if exception occurs } catch(ExceptionType1 e) { code to handle this type of exception } catch(ExceptionType2 e) { code to handle this type of exception } code after exception handing May throw either ExceptionType1 or ExceptionType2 Jump to appropriate catch block for type of exception that occurs Then skip to the first statement after all catch blocks
Java Exception Classes Exceptions are classes in Java ExceptionClass Division: 0 / 0 ArithmeticException A[index] outside bounds of array ArrayIndexOutOfBounds Exception Parsing non-numeric string Integer.parseInt(“Fred”) NumberFormatException object.method() for null object NullPointerException Access to nonexistent file IOException
Division Example Example: Prompt for 2 numbers, divide them and display result Key question: What types of exceptions may occur? String s1 = JOptionPane.showInputDialog(“Num: "); String s2 = JOptionPane.showInputDialog("Denom: "); int num = Integer.parseInt(s1); int den = Integer.parseInt(s2); int result = num/den; JOptionPane.showMessageDialog(null, "The result is "+result); May cause NumberFormatException May cause ArithmeticException
Division Example Other questions: –What other code should not be executed if exceptions occur? Should not divide numbers if numbers not entered Should not display result if division cannot be done Therefore, parsing, division, and display must be in same try block –How should exceptions be handled Print appropriate error messages Skip to final message
Division Example try { int num = Integer.parseInt(s1); int den = Integer.parseInt(s2); int result = num/den; JOptionPane.showMessageDialog(null, “Result: "+result); } catch(NumberFormatException numex) { JOptionPane.showMessageDialog(null, “Must be integers!"); } catch(ArithmeticException arex) { JOptionPane.showMessageDialog(null, "Undefined number!"); }
Division Example try { int num = Integer.parseInt(s1); int den = Integer.parseInt(s2); int result = num/den; JOptionPane.showMessageDialog(null, “Result: "+result); } catch(NumberFormatException numex) { JOptionPane.showMessageDialog(null, “Must be integers!"); } catch(ArithmeticException arex) { JOptionPane.showMessageDialog(null, "Undefined number!"); } User enters “fred” for second number
Division Example try { int num = Integer.parseInt(s1); int den = Integer.parseInt(s2); int result = num/den; JOptionPane.showMessageDialog(null, “Result: "+result); } catch(NumberFormatException numex) { JOptionPane.showMessageDialog(null, “Must be integers!"); } catch(ArithmeticException arex) { JOptionPane.showMessageDialog(null, "Undefined number!"); } User enters 0 for first and second number
Division Example try { int num = Integer.parseInt(s1); int den = Integer.parseInt(s2); int result = num/den; JOptionPane.showMessageDialog(null, “Result: "+result); } catch(NumberFormatException numex) { JOptionPane.showMessageDialog(null, “Must be integers!"); } catch(ArithmeticException arex) { JOptionPane.showMessageDialog(null, "Undefined number!"); } User enters 11 for first number and 5 for second
Unwinding the Stack What if exception not handled? –Exit current method –Throw exception to caller –Can handle exception at any level
Unwinding the Stack try { … int result = divide(num, den); JOptionPane.showMessageDialog(null, “Result: "+result); } … catch(ArithmeticException arex) { JOptionPane.showMessageDialog(null, "Undefined number!"); } … } public int divide(int a, int b) { return a/b; } 1) ArithmeticException thrown here, not handled here 2) so ArithmeticException thrown back to here call 3) And handled here
Unwinding the Stack What if exception not handled at any level? Stack completely “unwound” –Methods in side application –Button methods which called application… –Up to main Ultimately thrown to containing JVM –Prints message for each method unwound –Does not cause program crash!