Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.

Similar presentations


Presentation on theme: "Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA."— Presentation transcript:

1 Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA ‘99 Tutorial; internet notes; notes:H. Conrad Cunningham 5/25/2019 IT350

2 Exception Handling Exceptions are error conditions -- not bugs
a bug is a defect in the code an error condition is a predictable failure that occurs under certain circumstances Exceptions are the way a program can handle gracefully an error that would cause a crash. 5/25/2019 IT350

3 Exception Handling The Java language provides many exception handlers for programmer errors Java runtime system detects an exceptional event an Exception object is constructed containing info about exception type runtime system throws an exception runtime system looks for code to handle the exception if no handler found, program terminates 5/25/2019 IT350

4 Exception Handling Example: Java throws an exception when an invalid number is entered public class HandleException { public static void main ( String[] args ) TextReader keyboard = new TextReader(); System.out.println ( “Enter a number: “); String numberString = keyboard.readWord(); double number = Double.parseDouble( numberString ); System.out.println( numberString + “ stored in number as “ + number; ); } 5/25/2019 IT350

5 Exception Handling Dialogue when number entered is not valid:
Java displays a stack of method calls; main is the bottom of the stack the exception occurred in the method on the top Enter a number: 35o Exception in thread “main” java.lang.NumberFormatException: 35o at java.lang.FloatingDecimal.readJavaFormatString (FloatingDecimal.java:1176) at java.lang.Double.parseDouble(Double.java.184) at HandleException.main(HandleException.java.io) 5/25/2019 IT350

6 Exception Handling We don’t usually want the program to terminate, but rather to proceed with some alternative action in the event of an exception. So we write code to ‘catch’ the exception A ‘try’ block is wrapped around the code being executed. It is followed immediately by a ‘catch’ block, which contains code that executes in the event of an error. We also specify in the catch block what type of exception is being thrown 5/25/2019 IT350

7 Using try/catch to Handle Exceptions
public class HandleException { public static void main ( String[] args ) { TextReader keyboard = new TextReader(); System.out.println ( “Enter a number: “); String numberAsString = keyboard.readWord(); double number; try { number = Double.parseDouble( numberAsString ); } catch (NumberFormatException nfe) System.out.println(numberAsString + “ is not a valid number”); System.out.println(“Setting number to -1.0”); number = -1.0; System.out.println( numberAsString + “ stored in number as “+ number; ); 5/25/2019 IT350

8 Runtime Exceptions You must know when a method might throw an exception and what type of exception it throws. Read the documentation to find out! /** From Double class: * Return a floating-point number represented by the String * argument; If numberAsString does not represent a valid * number, this method will throw a number format * exception. */ public static double parseDouble(string numberAsString) throws NumberFormatException 5/25/2019 IT350

9 Handling an I/O Exception
If an I/O connection fails, Java throws an IOException. This is the method for a URL connection: public URLConnection() throws IOException Here’s the usage: java.net.URL url = new java.net.URL(“ java.net.URLConnection conn; try { conn = url.openConnection(); } catch ( java.io.IOException e ) { //an error has occurred; log an error, print a message or //throw another exception “If you do not explicitly catch the exception or throw a new exception, the exception will bubble up the stack until it reaches the top or someone finally catches it.” -- Sintes 5/25/2019 IT350

10 Unchecked Exceptions The parseDouble method does not catch the exception!! If the programmer does not put the method call in a try block and explicitly catch the exception, the program simply terminates (as shown in earlier example). This is one of the “unchecked” exceptions: one that doesn’t need to be handled many unchecked exception classes extend the RuntimeException class. 5/25/2019 IT350

11 Exceptions Classes Hierarchy
Object Handling exceptions in extending classes is optional Throwable Exception Error ClassNotFound Exception IOException RuntimeException ArithmeticException FileNotFound Exception ...EOFException... NumberFormatException IndexOutOfBoundsException NullPointerException ... 5/25/2019 IT350

12 Writing a Method That Throws an Exception
public void deposit (double anAmount ) throws IllegalArgumentException { if (anAmount <= 0.0) throw new IllegalArgumentException(); balance = balance + anAmount; } The keyword ‘throw’ must be followed by an instance of a class that extends Throwable. Because Exception extends Throwable, an instance of any Exception class can be thrown. 5/25/2019 IT350

13 Multiple Catch Statements
There may be multiple categories of exceptions that you want to catch Each category is a separate catch block try { //some code } catch (NullPointerException e1) { … } catch (IllegalArgumentException e2) { … } catch (Exception e3) { //This is a ‘catch-all’ -- catches any type of exception that can be thrown} finally { //this code is executed even if an exception did not occur //commonly used to clean up internal state (like closing a file) If no appropriate catch is found, the exception percolates out of the try statement into any outer try that might have a catch clause to handle it. If a finally clause is present with a try, its code is executed after all other processing in the try is complete. This happens no matter how completion was achieved -- whether through an exception or through a control flow statement such as return or break. Finally clause is commonly used to clean up internal state or to release non-object resources. e.g. finally { if (input != null) input.close(); } 5/25/2019 IT350


Download ppt "Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA."

Similar presentations


Ads by Google