Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 501N Fall ’09 17: Exception Handling

Similar presentations


Presentation on theme: "CSE 501N Fall ’09 17: Exception Handling"— Presentation transcript:

1 CSE 501N Fall ’09 17: Exception Handling
03 November 2009 Nick Leidenfrost

2 Lecture Outline Lab 6 Questions? Exceptions & Errors throws statement
Exception Handling: try/catch blocks finally statement

3 Error Handling: Error Codes
Traditional approach: Method returns error code public static final int NO_ERROR = 0; public static final int BAD_INPUT = -1; public static final int INVALID_STATE = -2; // ... public int doSomething (int someInput) { if (!isValidInput(someInput)) return BAD_INPUT; // ... Method body return 0; }

4 Error Handling: Error Codes
Problem: Caller is not forced to check for error code (Failure notification may go undetected) Problem: Calling method may not be able to do anything about failure Caller must also fail and let its caller worry about it Many method calls would need to be checked Lots of special logic would be introduced for handling errors

5 Error Handling: Error Codes
Instead of programming for success: You would always be programming for failure: int theAnswer = x.doSomething(0); IntStorage answer = new IntStorage(0); int errorCode = x.doSomething(0, answer); if (errorCode != x.NO_ERROR) return errorCode;

6 Error Handling Java provides two ways of dealing with abnormal circumstances: Exceptions “… conditions that a … program might want to catch” Derived from java.lang.Exception Errors “… serious problems that a … program should not try to catch” Derived from java.lang.Error

7 We throw an exception with the throw clause.
Throwing Exceptions Exceptions: Alter control flow to code intended to deal with the problem: Exception handlers Can't be overlooked Java compiler checks for existence of exception handlers Throw an exception object to signal an exceptional condition (or abnormal condition) Example: IllegalArgumentException: Method execution is halted at this point and control flow is returned to the calling method. We throw an exception with the throw clause. // illegal parameter value Exception iaException = new IllegalArgumentException(“Key cannot be null."); throw iaException;

8 Throwing Exceptions No need to store exception object in a variable:
When an exception is thrown, method terminates immediately Execution continues with an exception handler which handles the type of exception that was thrown throw new IllegalArgumentException(“Key cannot be null.“);

9 Example public class HashMap { public void put (Object key, Object value) { if (key == null) { IllegalArgumentException exception = new IllegalArgumentException(“Key cannot be null.“); throw exception; } // ... } }

10 Types of Exceptions Two types of exceptions: Checked Unchecked
The compiler will check to make sure code exists to handle the exception Unchecked Usually arise in circumstances that would be impossible for the compiler to predict A.k.a. Runtime exceptions [ Eclipse Example ]

11 Hierarchy of Exception Classes
The Hierarchy of Exception Classes

12 Checked vs. Unchecked Exceptions
Usually due to external circumstances that the programmer cannot prevent The compiler checks that you don't ignore them outright You must define exception handlers Mainly occur when dealing with input and output For example, IOException caused by File manipulation, Networking, user input, etc.

13 Checked vs. Unchecked Exceptions
Unchecked Exceptions / Errors: Extend the class RuntimeException or Error They are (usually) the programmer's fault Examples of runtime exceptions: Example of error: OutOfMemoryError NullPointerException ArrayIndexOutOfBoundsException IllegalArgumentException

14 Checked vs. Unchecked Exceptions
Categories aren't perfect: Scanner.nextInt throws unchecked InputMismatchException Programmer cannot prevent users from entering incorrect input This choice makes the class easy to use for beginning programmers Deal with checked exceptions principally when programming with files and streams Coming up in a few lectures… [ Eclipse Scanner Example ]

15 The throws clause If an exception can be thrown, the compiler will make sure our code acknowledges the exception Two choices: Handle the exception in this method We’ll look at how to do this in a bit… Tell compiler that you want method to be terminated when the exception occurs Use throws keyword to tell Java an exception may be thrown inside the method body that is not handled public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); }

16 The throws clause For multiple exceptions:
Keep in mind inheritance hierarchy: If method can throw an IOException and FileNotFoundException, only use IOException Better to declare exception than to handle it incompetently public void read(String filename) throws IOException, ClassNotFoundException

17 Syntax: Exception Specification
accessSpecifier returnType methodName(parameterType parameterName, . . .) throws ExceptionClass, ExceptionClass, . . . Example:  public void read(BufferedReader in) throws IOException Purpose: To indicate the checked exceptions that this method can throw

18 Exception Handlers Catching Exceptions
Write exception handlers with the try/catch statement try block contains statements that may cause an exception catch clause contains handler for an exception type

19 Catching Exceptions: Syntax
try { // Code that might cause Exceptions } catch (Exception exception) { // Code to handle Exceptions

20 Catching Exceptions: control flow
Statements in try block are executed If no exceptions occur, catch clauses are skipped If exception of matching type occurs, execution jumps to catch clause If exception of another type occurs, it is thrown until it is caught by another try/catch block

21 Catching Exceptions: the catch clause
catch (IOException exception) { } exception contains reference to the exception object that was thrown catch clause can analyze object to find out more details exception.printStackTrace(): printout of chain of method calls that lead to exception

22 Catching Errors: the catch clause
It is possible to catch Errors, also. Because Errors are typically indicative of more serious problems, doing this is rare. Most often, the program is allowed to terminate. try { ... } catch (Error error) {

23 Syntax: Multiple catch clauses
try { // statement // . . . } catch (ExceptionClass exceptionObject) {

24 Catching Multiple Types of Exceptions
Throws java.lang.IOException try { String filename = “. . .”; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); } Throws java.lang.NumberFormatException catch (Exception exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }

25 The finally clause An uncaught exception terminates the current method
- ! - This can skip over essential code Example: public void readSomeData () throws IOException { FileReader reader = new FileReader(filename); Scanner input = new Scanner(reader); readData(input); // Can throw an exception reader.close(); // May never get here }

26 The finally clause We want to execute reader.close() even if an exception happens Use finally clause for code that must be executed "no matter what"

27 Example: The finally clause
FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } catch (IOException ioe) { // ... } finally { reader.close(); // finally clause is executed regardless // of whether exception occurs }

28 Syntax: The finally clause
try { // statements } finally { // Notice that a try block can have a finally clause without a catch // Why is this?

29 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, if this try block caught an exception When an exception was thrown in try block and not caught For any of these ways, the finally block executes.

30 Designing Your Own Exception Types
You can design your own exception types–subclasses of Exception or RuntimeException Checked Exceptions Unchecked Exceptions if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); }

31 Designing Your Own Exception Types
Make it an unchecked exception–programmer could have avoided it by calling getBalance first Extend RuntimeException or one of its subclasses (InvalidParameterException) Supply two constructors Default constructor A constructor that accepts a message string describing reason for exception

32 Designing Your Own Exception Types
public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException (String message, double shortage) { super(message); } } public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException (String message) { super(message); } } Your type can include additional information needed to handle properly

33 Conclusion Questions? Lab 6 Due Tonight at Midnight
Lab 7 Assigned Today Due 11/10 at Midnight Lab Now


Download ppt "CSE 501N Fall ’09 17: Exception Handling"

Similar presentations


Ads by Google