38
COMP 121 Week 5: Exceptions and Exception Handling

COMP 121 Week 5: Exceptions and Exception Handling

Embed Size (px)

Citation preview

Page 1: COMP 121 Week 5: Exceptions and Exception Handling

COMP 121

Week 5: Exceptions and Exception Handling

Page 2: COMP 121 Week 5: Exceptions and Exception Handling

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

Page 3: COMP 121 Week 5: Exceptions and Exception Handling

Error Handling Traditional approach -- Method returns

a value to indicate success or failureThe 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 (3rd ed.). New York: John Wiley & Sons.

Page 4: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 5: COMP 121 Week 5: Exceptions and Exception Handling

Java Solution: Exceptions

ExceptionsCan'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 (3rd ed.). New York: John Wiley & Sons.

Page 6: COMP 121 Week 5: Exceptions and Exception Handling

Exception Examplepublic void withdraw(double amount)

{

if (amount > balance)

{

IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception;

}

balance = balance - amount;

}

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

Page 7: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 8: COMP 121 Week 5: Exceptions and Exception Handling

Hierarchy of Exception Classes

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

Page 9: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 10: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 11: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 12: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 13: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 14: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 15: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 16: COMP 121 Week 5: Exceptions and Exception Handling

Example of Catching Exceptionstry { 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 (3rd ed.). New York: John Wiley & Sons.

Page 17: COMP 121 Week 5: Exceptions and Exception Handling

General try/catch Syntaxtry{ statement statement . . . } catch (ExceptionClass exceptionObject){ statement statement . . .} catch (ExceptionClass exceptionObject){ statement statement . . .}. . .

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

Page 18: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 19: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 20: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 21: COMP 121 Week 5: Exceptions and Exception Handling

Question:

How do you know what exceptions may be thrown?

Page 22: COMP 121 Week 5: Exceptions and Exception Handling

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 http://java.sun.com/javase/6/docs/api/

Page 23: COMP 121 Week 5: Exceptions and Exception Handling

Javadoc for Java Platform SE 6

Page 24: COMP 121 Week 5: Exceptions and Exception Handling

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

Page 25: COMP 121 Week 5: Exceptions and Exception Handling

Answer: FileNotFoundException

Page 26: COMP 121 Week 5: Exceptions and Exception Handling

Question:What is the superclass of FileNotFoundException?

Page 27: COMP 121 Week 5: Exceptions and Exception Handling

Answer: IOException

Page 28: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 29: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 30: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 31: COMP 121 Week 5: Exceptions and Exception Handling

The finally clause

try{ statement statement . . .}finally{ statement statement . . .}

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

Page 32: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 33: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 34: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 35: COMP 121 Week 5: Exceptions and Exception Handling

Designing Your Own Exception Classes

public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {}

public InsufficientFundsException(String message) { super(message); } }

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.

Page 36: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 37: COMP 121 Week 5: Exceptions and Exception Handling

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 (3rd ed.). New York: John Wiley & Sons.

Page 38: COMP 121 Week 5: Exceptions and Exception Handling

Any Questions?