CSE 501N Fall ‘06 02: Machine Overview + Fundamental Types

Download Report

Transcript CSE 501N Fall ‘06 02: Machine Overview + Fundamental Types

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

Lecture Outline

 Lab 6 Questions?

 Exceptions & Errors 

throws

statement  Exception Handling: 

finally

statement

try

/

catch

blocks

2

Error Handling: Error Codes

 Traditional approach:  Method returns error code

public static final int public static final int public static final int // ...

NO_ERROR = 0; BAD_INPUT = -1; INVALID_STATE = -2;

public int

doSomething (

int

someInput) {

if

(!isValidInput(someInput))

return // ... Method body return

0; BAD_INPUT; }

3

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

4

Error Handling: Error Codes

 Instead of programming for success:

int

theAnswer = x.doSomething(0);  You would always be programming for failure: IntStorage answer = new IntStorage(0);

int

errorCode = x.doSomething(0, answer);

if

(errorCode != x.NO_ERROR)

return

errorCode;

5

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

6

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:

// illegal parameter value

Exception iaException = exception with the

new

halted at this point and control flow is returned to the calling method.

IllegalArgumentException( “ Key cannot be null." );

throw

iaException;

7

Throwing Exceptions

 No need to store exception object in a variable:

throw new

IllegalArgumentException( “Key cannot be null.“ );  When an exception is thrown, method terminates immediately  Execution continues with an exception handler which handles the type of exception that was thrown

8

Example

public class

HashMap {

public void if

put (Object key, Object value) { (key == IllegalArgumentException exception =

null new

) { IllegalArgumentException( “Key cannot

throw

}

// ...

be null.“ ); exception; } }

9

Types of Exceptions

 Two types of exceptions:  Checked  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 ]

10

Hierarchy of Exception Classes

The Hierarchy of Exception Classes 11

Checked vs. Unchecked Exceptions

 Checked 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.

12

Checked vs. Unchecked Exceptions

 Unchecked Exceptions / Errors:  Extend the class RuntimeException or  They are (usually) the programmer's fault  Examples of runtime exceptions: Error

NullPointerException ArrayIndexOutOfBoundsException IllegalArgumentException

 Example of error: OutOfMemoryError

13

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

[ Eclipse Scanner Example ]

 Deal with checked exceptions principally when programming with files and streams  Coming up in a few lectures…

14

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

FileReader reader =

new

FileNotFoundException { FileReader(filename); Scanner in = . . .

new

Scanner(reader); }

15

The

throws

clause

 For multiple exceptions:

public void throws

read(String filename) IOException, ClassNotFoundException  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

16

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 17

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

18

Catching Exceptions: Syntax

try

{

// Code that might cause Exceptions

}

catch

(Exception exception) {

// Code to handle Exceptions

}

19

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

20

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

21

Catching Errors: the catch clause

 It is possible to catch Errors, also.

try

{ ...

}

catch

(Error error) { }  Because Errors are typically indicative of more serious problems, doing this is rare.

 Most often, the program is allowed to terminate.

22

Syntax: Multiple catch clauses

try

{

// statement

// . . .

}

catch

(

ExceptionClass exceptionObject

) {

// statement // . . .

}

catch

(

ExceptionClass exceptionObject

) {

// statement // . . .

}

23

Catching Multiple Types of Exceptions

try { String filename = “. . .”;

Throws java.lang.IOException

FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . . }

Throws java.lang.NumberFormatException

catch (IOException exception) { exception.printStackTrace(); catch (NumberFormatException exception) { System.out.println("Input was not a number"); } 24

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

Scanner input =

new

FileReader(filename); 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 try

{ Scanner in = new Scanner(reader); readData(in); }

catch

FileReader(filename); (IOException ioe) {

// ...

}

finally

{ reader.close();

// finally clause is executed regardless // of whether exception occurs

}

28

Syntax: The

finally

clause

try

{

// statements

}

finally

{

// statements

}

// Notice that a try block can have a finally clause without a catch // Why is this? 29

The

finally

clause

  Executed when

try

three ways: block is exited in any of  After last statement of

try

block  After last statement of

catch

caught an exception clause, if this

try

 When an exception was thrown in

try

caught block block and not For any of these ways, the

finally

executes.

block

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 ) 1.

Supply two constructors Default constructor 2.

A constructor that accepts a message string describing reason for exception

32

Designing Your Own Exception Types

public class

InsufficientFundsException

public class InsufficientFundsException extends

RuntimeException {

extends RuntimeException { }

}

public

InsufficientFundsException() {}

public InsufficientFundsException() {} public

InsufficientFundsException (String message,

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

shortage) {

}

}

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

34