Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 121 Week 5: Exceptions and Exception Handling.

Similar presentations


Presentation on theme: "COMP 121 Week 5: Exceptions and Exception Handling."— Presentation transcript:

1 COMP 121 Week 5: Exceptions and Exception Handling

2 Objectives To learn how to throw exceptions To understand the difference between checked and unchecked exceptions To learn how to catch exceptions To know when and where to catch an exception To learn how to create your own exception classes

3 Error Handling Traditional approach -- Method returns a value to indicate success or failure  The calling method may not check return value Failure notification may go undetected  The calling method may not be able to do anything about failure Calling method must fail, too, and let its caller worry about it Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

4 Error Handling Instead of programming for success: You are always programming for failure: x.doSomething(); if (!x.doSomething()) return false; Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

5 Java Solution: Exceptions Exceptions  Can't be overlooked  Are sent directly to an exception handler – not just the caller of failed method To signal an exceptional condition, use throw statement to throw an exception Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

6 Exception Example public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

7 Throwing Exceptions No need to store exception object in a variable: When an exception is thrown, the method that threw the exception terminates immediately  Execution continues with an exception handler throw new IllegalArgumentException("Amount exceeds balance"); Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

8 Hierarchy of Exception Classes Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

9 Checked and Unchecked Exceptions Checked Exceptions  Compiler checks that you take care of a checked exception if you call a method that throws one  Due to external circumstances that the programmer cannot prevent  Majority occur when dealing with input and output  A checked exception is not a subclass of RuntimeException or Error Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

10 Checked and Unchecked Exceptions Unchecked Exceptions  Compiler does not check that you take care of an unchecked exception if you call a method that throws one  Due to circumstances that the programmer can prevent  An unchecked exception is a subclass of RuntimeException or Error Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

11 Checked and Unchecked Exceptions Categories aren't perfect:  Scanner.nextInt throws unchecked InputMismatchException  Programmer cannot prevent users from entering incorrect input Majority of checked exceptions deal with input and output (files and streams) Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

12 Checked and Unchecked Exceptions For example, use a Scanner to read a file FileReader constructor can throw a FileNotFoundException (checked exception) String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

13 Options for Checked Exceptions Two choices:  Handle the exception  Tell compiler that you want the method to be terminated when the exception occurs Your method doesn’t handle the exception, so it throws the exception up to its caller Use throws specifier when method can throw a checked exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);... } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

14 Options for Checked Exceptions A single method can throw multiple exceptions  Use throws with exception separated by commas: Keep in mind the inheritance hierarchy:  If method can throw an IOException and FileNotFoundException, only use IOException (superclass of FileNotFoundException ) Better to throw an exception you don’t know how to handle than handle it incorrectly or incompletely public void read(String filename) throws IOException, ClassNotFoundException Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

15 Catching Exceptions Install an exception handler with try/catch statement try block contains statements that may cause an exception catch clause contains the handler for a certain type of exception May have multiple catch clauses for the different types of exceptions Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

16 Example of Catching Exceptions try { String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input);... } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

17 General try/catch Syntax try { statement... } catch (ExceptionClass exceptionObject) { statement... } catch (ExceptionClass exceptionObject) { statement... }... Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

18 Catching Exceptions Statements in try block are executed If no exceptions occur, catch clauses are skipped If an exception matching a caught type occurs, execution jumps to catch clause that matches  After the catch block is executed, the method continues with the code after the entire try/catch statement If exception that doesn’t match a caught type occurs, it is thrown until it is caught by another try block ( try blocks can be nested) If an exception is not caught, it eventually will terminate the program Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

19 Catch Block catch ( ExceptionClass exception)  ExceptionClass is the actual type (class name) of the exception being caught  exception contains reference to the exception object that was thrown  catch clause can analyze object to find out more details exception.printStackTrace()  Prints out the chain of method calls that led to the exception exception.getMessage()  Retrieves the message string from the exception Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

20 Flow of Control with try/catch try { // beginning of try block Foo f = myobj.doSomething(); // doSomething may throw an exception int x = f.getNum(); // will get here only if doSomething succeeded } // end of try block catch (Exception ex) { // beginning of catch System.out.println(“doSomething failed”); // displayed if doSomething failed ex.printStackTrace(); // displays stack } // end of catch block System.out.printlin(“End of try/catch”); // No exception or caught exception Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

21 Question: How do you know what exceptions may be thrown?

22 Answer: Compile your code, and the compiler will let you know (if it is a checked exception) Read the javadoc!  Installed when Java was installed on the system file:///c:/Program%20Files/Java/jdk1.6.0/docs/api/index.html  Also available on the Internet

23 Javadoc for Java Platform SE 6

24 Question: What exception(s) may be thrown when a FileReader object is constructed?

25 Answer: FileNotFoundException

26 Question:What is the superclass of FileNotFoundException ?

27 Answer: IOException

28 The finally clause Exception terminates current method  May cause the JVM to skip over essential code Example: PrintWriter out = new PrintWriter(filename); writeData(out); out.close(); // May never get here Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

29 The finally clause Use optional finally clause for code that must be executed no matter what Once a try block is entered, the statements in the finally clause are guaranteed to execute whether an exception is thrown or not Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

30 The finally clause PrintWriter out = new PrintWriter(filename); try { writeData(out); } finally { out.close(); // if an exception occurs, finally clause // is executed before exception is // passed to its handler. Also executed // if no exception occurs. } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

31 The finally clause try { statement... } finally { statement... } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

32 The finally clause Executed when try block is exited in any of three ways:  After last statement of try block  After last statement of catch clause that caught the exception, if one was thrown  When an exception was thrown in try block and was not caught Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

33 You can design your own exception types–subclasses of Exception or RuntimeException It is an unchecked exception–programmer could have avoided it by calling getBalance and checking first Designing Your Own Exception Classes if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

34 In your exception class  Extend RuntimeException or one of its subclasses  Supply two constructors 1. Default constructor 2. A constructor that accepts a message string describing reason for exception Designing Your Own Exception Classes Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

35 Designing Your Own Exception Classes public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

36 Guidelines for Exceptions To signal an exceptional condition, use the throw statement to throw an exception object  Throw the most specific exception type you can Add a throws specifier to any method that can throw a checked exception  It is better to declare that a method throws a checked exception than to handle it poorly  Do not “squelch” exceptions by catching the exception and then doing nothing To handle an exception, put the code that can cause the exception inside a try block, and put the handler code inside the catch  Only catch an exception if you know how to handle it Design your own exception classes as subclasses of Exception or RuntimeException only if the standard exception types don’t adequately describe the error Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

37 Summary An exception is used to signal an error condition When an exception is thrown, the current method terminates immediately There are two kinds of exceptions: checked and unchecked  The compiler checks that your program handles checked exceptions  Unchecked exceptions extend the class RuntimeException or Error Statements that can cause an exception can be put inside a try block  A catch clause is used to handle the exception  A finally clause is used for code that is guaranteed to execute, whether or not an exception is thrown Horstmann, C. (2008). Big Java (3 rd ed.). New York: John Wiley & Sons.

38 Any Questions?


Download ppt "COMP 121 Week 5: Exceptions and Exception Handling."

Similar presentations


Ads by Google