55
Chapter 15 – Chapter 15 – Exception Exception Handling Handling

Chapter 15 – Exception Handling

  • Upload
    lupita

  • View
    31

  • Download
    1

Embed Size (px)

DESCRIPTION

Chapter 15 – Exception Handling. 15.1 Throwing Exceptions. What is a good program? A program that is reliable. Not just giving correct answer on correct input Should protect against possible errors (invalid password, not a picture file, etc). Good programs. - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 15 – Exception Handling

Chapter 15 – Exception Chapter 15 – Exception HandlingHandling

Page 2: Chapter 15 – Exception Handling

What is a good program? A program What is a good program? A program that is reliable.that is reliable.

Not just giving correct answer on Not just giving correct answer on correct inputcorrect input

Should protect against possible errors Should protect against possible errors (invalid password, not a picture file, (invalid password, not a picture file, etc)etc)

15.1 Throwing Exceptions15.1 Throwing Exceptions

Page 3: Chapter 15 – Exception Handling

Good programsGood programs

Need a robust program, reliable to Need a robust program, reliable to the userthe user

It should not (“cannot”) crash easilyIt should not (“cannot”) crash easily

Page 4: Chapter 15 – Exception Handling

How do we do this?How do we do this?

Option 1 – return a special value to Option 1 – return a special value to determine if the method succeeded determine if the method succeeded or failedor failed– Ex. Make withdraw return true or falseEx. Make withdraw return true or false

What’s wrong with this?What’s wrong with this?– Calling method may not check answerCalling method may not check answer– Calling method may not know what to Calling method may not know what to

dodo

Page 5: Chapter 15 – Exception Handling

Catching ExceptionsCatching Exceptions

ExceptionException – an error condition that can – an error condition that can occur during the normal course of a occur during the normal course of a program executionprogram execution

In Java, exceptions are objects themselvesIn Java, exceptions are objects themselves Exception handlingException handling is another form of is another form of

control structure (like ifs and switch control structure (like ifs and switch statements)statements)– When an error is encountered, the normal flow When an error is encountered, the normal flow

of the program is stopped and the exception is of the program is stopped and the exception is handledhandled

Page 6: Chapter 15 – Exception Handling

ExceptionsExceptions

We say an exception is We say an exception is thrownthrown when it when it occursoccurs

When the exception-handling code is When the exception-handling code is executed, the error is executed, the error is caughtcaught

Examples:Examples:– Divide by zeroDivide by zero– Access a null objectAccess a null object– Array Index Out of BoundsArray Index Out of Bounds

Page 7: Chapter 15 – Exception Handling

Exception Program FlowException Program Flow

What happens when exceptions occur?What happens when exceptions occur?– An Exception object is thrownAn Exception object is thrown

What happens when an Exception is What happens when an Exception is thrown?thrown?– normal execution stops and exception handling normal execution stops and exception handling

beginsbegins

What does the Exception object know?What does the Exception object know?– the name of the problemthe name of the problem– the location where it occurredthe location where it occurred– and more…and more…

Page 8: Chapter 15 – Exception Handling

Why have exception handling?Why have exception handling? consistency (everyone else does it)consistency (everyone else does it)

– Java API classes use exceptions.Java API classes use exceptions.– Other programming languages do too!Other programming languages do too!

flexibilityflexibility– Programmer can decide how to fix problems.Programmer can decide how to fix problems.

simplicitysimplicity– Easy to pinpoint problems.Easy to pinpoint problems.

Page 9: Chapter 15 – Exception Handling

FoodIterator fi = afc.getAllFood();FoodIterator fi = afc.getAllFood(); while ( !hasFood() && fi.hasNext() ) {while ( !hasFood() && fi.hasNext() ) { Food f = fi.getNextFood();Food f = fi.getNextFood(); if ( f.getLocation().equals(myLoc) )if ( f.getLocation().equals(myLoc) ) myFood=f;myFood=f; }} }}

What exceptions can occur?What exceptions can occur?

NullPointerException

Page 10: Chapter 15 – Exception Handling

public double divide( int data1, int data2 ){

return data1 / data2;}

What exceptions can occur?What exceptions can occur?

Arithmetic Exception: divide by zero

Page 11: Chapter 15 – Exception Handling

How to handle Exceptions?How to handle Exceptions?

Do nothingDo nothing program crashes if the exception occurs!program crashes if the exception occurs!

Propagate (throws) itPropagate (throws) it tell the method’s caller about it and let them tell the method’s caller about it and let them

decide what to dodecide what to do

Resolve (try-catch) it in our methodResolve (try-catch) it in our method fix it or tell the user about it and let them fix it or tell the user about it and let them

decide what to dodecide what to do

Page 12: Chapter 15 – Exception Handling

ExceptionsExceptions

So far, we have let the system handle So far, we have let the system handle exceptionsexceptionsint score = in.nextInt();int score = in.nextInt();

If the user enters If the user enters “abc123”“abc123”

Exception in thread "main" Exception in thread "main" java.util.InputMismatchExceptionjava.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:819)at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431)at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040)at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000)at java.util.Scanner.nextInt(Scanner.java:2000) at Test.main(Test.java:5)at Test.main(Test.java:5)

Page 13: Chapter 15 – Exception Handling

Says in English:Says in English:– System has caught an error described as a System has caught an error described as a InputMismatchExceptionInputMismatchException

– Thrown because a String cannot be Thrown because a String cannot be converted to an integerconverted to an integer

When system handles, we often get a When system handles, we often get a program crashprogram crash

Instead of the system, we can handle to Instead of the system, we can handle to improve robustnessimprove robustness

Page 14: Chapter 15 – Exception Handling

Throwing ExceptionsThrowing Exceptions

If there is an error in the value of a If there is an error in the value of a parameter, we can throw exceptions parameter, we can throw exceptions to make the user accountableto make the user accountable

1.1. Decide what type of exception to Decide what type of exception to throwthrow

2.2. Test for condition, and throw the Test for condition, and throw the exception if condition is violatedexception if condition is violated

Page 15: Chapter 15 – Exception Handling

ExampleExample

Throw an exception object to signal Throw an exception object to signal an exceptional condition an exceptional condition

Example: What do we do if the Example: What do we do if the amount to withdraw is greater than amount to withdraw is greater than the balance?the balance?– IllegalArgumentExceptionIllegalArgumentException: illegal parameter : illegal parameter

valuevalue

Page 16: Chapter 15 – Exception Handling

ProblemProblempublic class BankAccountpublic class BankAccount

{{

public void withdraw(double public void withdraw(double amountamount))

{{

if (if (amountamount > > balancebalance))

{{

??????????????????

}}

balance = balance - amount;balance = balance - amount;

} }

. . .. . .

} }

Page 17: Chapter 15 – Exception Handling

Solution #1Solution #1public class BankAccountpublic class BankAccount

{{

public void withdraw(double public void withdraw(double amountamount))

{{

if (if (amountamount > > balancebalance))

{{

IllegalArgumentException IllegalArgumentException exceptionexception = new IllegalArgumentException("Amount = new IllegalArgumentException("Amount

exceeds balance");exceeds balance");

throw throw exceptionexception;;

}}

balance = balance - amount;balance = balance - amount;

} }

. . .. . .

} }

Page 18: Chapter 15 – Exception Handling

Solution #2Solution #2public class BankAccountpublic class BankAccount

{{

public void withdraw(double public void withdraw(double amountamount))

{{

if (if (amountamount > > balancebalance))

{{

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

}}

balance = balance - amount;balance = balance - amount;

} }

. . .. . .

} }

Page 19: Chapter 15 – Exception Handling

15.2 Checked/Unchecked 15.2 Checked/Unchecked ExceptionsExceptions

Checked Exception – checked at Checked Exception – checked at compile timecompile time– Complier ensures that you are handling Complier ensures that you are handling

a possible problema possible problem– Due to external circumstances that the Due to external circumstances that the

programmer cannot prevent programmer cannot prevent – Majority occur when dealing with input Majority occur when dealing with input

and output and output – For example, IOException For example, IOException

Page 20: Chapter 15 – Exception Handling

Unchecked Exception – Runtime Unchecked Exception – Runtime ExceptionsExceptions– Extend the class Extend the class RuntimeExceptionRuntimeException or or ErrorError – They are the programmer's fault They are the programmer's fault – Examples of runtime exceptions: Examples of runtime exceptions:

NumberFormatExceptionNumberFormatExceptionIllegalArgumentExceptionIllegalArgumentExceptionNullPointerException NullPointerException

– Optional to deal with theseOptional to deal with these Example of error: Example of error: OutOfMemoryError OutOfMemoryError

– Can’t do anything about these catastrophic Can’t do anything about these catastrophic problems, so don’t deal with itproblems, so don’t deal with it

Page 21: Chapter 15 – Exception Handling
Page 22: Chapter 15 – Exception Handling

Why the differenceWhy the difference

Unchecked Exceptions result from Unchecked Exceptions result from deficiencies in your code, so should check deficiencies in your code, so should check on ownon own– Null object referenceNull object reference– Sending a negative value to Math.sqrt()Sending a negative value to Math.sqrt()

Checked Exceptions are not the fault of Checked Exceptions are not the fault of the coderthe coder– Problems with the file format, user input, etc.Problems with the file format, user input, etc.

Page 23: Chapter 15 – Exception Handling

Categories aren't perfect: Categories aren't perfect: – Scanner.nextIntScanner.nextInt throws unchecked throws unchecked InputMismatchException InputMismatchException

– Programmer cannot prevent users from Programmer cannot prevent users from entering incorrect input entering incorrect input

– This choice makes the class easy to use This choice makes the class easy to use for beginning programmersfor beginning programmers

Page 24: Chapter 15 – Exception Handling

Deal with checked exceptions Deal with checked exceptions principally when programming with principally when programming with files and streams files and streams

For example, use a For example, use a ScannerScanner to read a file to read a fileString filename = . . .; String filename = . . .;

FileReader reader = new FileReader(filename); FileReader reader = new FileReader(filename);

Scanner in = new Scanner(reader);Scanner in = new Scanner(reader); But, But, FileReaderFileReader constructor can throw a constructor can throw a FileNotFoundException FileNotFoundException

Page 25: Chapter 15 – Exception Handling

How do we deal with a checked How do we deal with a checked Exception?Exception?

1.1. Handle the exception Handle the exception 2.2. Tell compiler that you want method Tell compiler that you want method

to be terminated when the to be terminated when the exception occurs exception occurs

– Use Use throwsthrows specifier so method can specifier so method can throw a checked exceptionthrow a checked exception

public void read(String filename) throws public void read(String filename) throws FileNotFoundExceptionFileNotFoundException

{{FileReader reader = new FileReader reader = new FileReader(filename); FileReader(filename); Scanner in = new Scanner(reader);Scanner in = new Scanner(reader);. . .. . .

}}

Page 26: Chapter 15 – Exception Handling

This tells the compiler to “pass the buck” to This tells the compiler to “pass the buck” to the method that called this methodthe method that called this method

Can Can propagatepropagate multiple exceptions: multiple exceptions: public void read(String filename) throws IOException, public void read(String filename) throws IOException,

ClassNotFoundException ClassNotFoundException

Can also group using heirarchyCan also group using heirarchy– If method can throw an If method can throw an IOExceptionIOException and and FileNotFoundExceptionFileNotFoundException, only use , only use IOExceptionIOException

Page 27: Chapter 15 – Exception Handling

Why propagate?Why propagate?

Why not handle ourselves?Why not handle ourselves?– We may not know how toWe may not know how to– Let use of my code decideLet use of my code decide

Better to declare exception than to Better to declare exception than to handle it incompetently handle it incompetently

Page 28: Chapter 15 – Exception Handling

15.3 Catching Exceptions15.3 Catching Exceptions

At some point, an exception should be At some point, an exception should be dealt withdealt with– If not, program terminates with error If not, program terminates with error

messagemessage Professional code requires more Professional code requires more

sophistication – cannot just allow sophistication – cannot just allow errors to kill programerrors to kill program– What would happen if all of my.wisc.edu What would happen if all of my.wisc.edu

turned off if you entered wrong password?turned off if you entered wrong password?

Page 29: Chapter 15 – Exception Handling

SolutionSolution

Install exception handlers in your Install exception handlers in your code to deal with possible exceptionscode to deal with possible exceptions

Handlers are try/catch statementsHandlers are try/catch statements

Page 30: Chapter 15 – Exception Handling

Try-CatchTry-Catch

Put statement(s) that could cause an Put statement(s) that could cause an error in the error in the trytry block block

Error handling code goes in Error handling code goes in catch catch blockblock– Only is executed if there was an errorOnly is executed if there was an error

Can have multiple catch blocks, one for Can have multiple catch blocks, one for each possible type of exceptioneach possible type of exception

Page 31: Chapter 15 – Exception Handling

try-catchtry-catch Syntax Syntaxtry try {{ <try block><try block>}}catchcatch ( <ExceptionClass> <name> ) ( <ExceptionClass> <name> ) {{ <catch block><catch block>}}catchcatch ( <ExceptionClass> <name> ) ( <ExceptionClass> <name> ) {{ <catch block><catch block>}…}…

Page 32: Chapter 15 – Exception Handling

trytry

{{

String filename = “myfile.txt”; String filename = “myfile.txt”;

FileReader reader = new FileReader(filename);FileReader reader = new FileReader(filename);

Scanner in = new Scanner(reader);Scanner in = new Scanner(reader);

String input = in.next();String input = in.next();

int value = Integer.parseInt(input);int value = Integer.parseInt(input);

. . .. . .

}}

catch (IOException exception)catch (IOException exception)

{{

exception.printStackTrace();exception.printStackTrace();

}}

catch (NumberFormatException exception)catch (NumberFormatException exception)

{{

System.out.println("Input was not a number");System.out.println("Input was not a number");

} }

Page 33: Chapter 15 – Exception Handling

3 types3 types

3 types of error can be thrown3 types of error can be thrown– FileNotFoundExceptionFileNotFoundException is thrown by is thrown by FileReader FileReader constructor constructor caught by caught by IOExceptionIOException clause clause

– NoSuchElementExceptionNoSuchElementException is thrown by is thrown by Scanner.nextScanner.next not caught, thrown to not caught, thrown to callercaller

– NumberFormatExceptionNumberFormatException is thrown by is thrown by Integer.parseInt()Integer.parseInt() caught by second caught by second clauseclause

Page 34: Chapter 15 – Exception Handling

Execution FlowExecution Flow

If there are no errors, the catch block If there are no errors, the catch block is skippedis skipped

If an exception is thrown, the try If an exception is thrown, the try block stops executing block stops executing immediatelyimmediately, , jumps to catch blockjumps to catch block

Page 35: Chapter 15 – Exception Handling
Page 36: Chapter 15 – Exception Handling

Exception objectsException objects

Why do we create an instance of the Why do we create an instance of the exception?exception?– We can get information on the specific We can get information on the specific

exception causeexception cause

2 methods defined (from the 2 methods defined (from the Throwable superclass): Throwable superclass): – getMessage() (what happened?)getMessage() (what happened?)– printStackTrace() (where did it happen?)printStackTrace() (where did it happen?)

Page 37: Chapter 15 – Exception Handling

getMessagegetMessage

Returns the data that cause the errorReturns the data that cause the error– Example:Example:

……}catch(NumberFormatException e){}catch(NumberFormatException e){

System.out.println(e.getMessage());System.out.println(e.getMessage());

}}

Page 38: Chapter 15 – Exception Handling

printStackTraceprintStackTrace

Prints out a trace of methods that Prints out a trace of methods that caused the error starting at the root of caused the error starting at the root of the errorthe error– Where did the exception occur? What Where did the exception occur? What

method called this code to execute..etc.method called this code to execute..etc.– What the System does when an exception What the System does when an exception

is thrownis thrown– Example:Example:catch(NumberFormatException e){catch(NumberFormatException e){

e.printStackTrace();e.printStackTrace();

}}

Page 39: Chapter 15 – Exception Handling

public double average( String data ){

int sum = 0;for ( int i=0; i < data.length(); i++ )

sum += Integer.parseInt(data.charAt(i));return sum/data.length();

}

Catch ALL exceptions (bad idea)Catch ALL exceptions (bad idea)

trytry

{{

}} catch ( Exception e ) // catch ALL exceptions{

System.out.println( e.printStackTrace() );return 0;

}

Page 40: Chapter 15 – Exception Handling

Throwable ExceptionsThrowable Exceptions

IMPORTANT! Order of catch blocks mattersIMPORTANT! Order of catch blocks matters} catch} catch (Exception e){ (Exception e){

System.out.println(e.getMessage());System.out.println(e.getMessage());

} catch } catch (NumberFormatException e)(NumberFormatException e){{

System.out.println("'" + str + "'not valid System.out.println("'" + str + "'not valid input, Please use digits only");input, Please use digits only");

}}

You should go specific to genericYou should go specific to generic– NumberFormatException is a specific type of NumberFormatException is a specific type of

the class Exception (inheritance)the class Exception (inheritance)

Page 41: Chapter 15 – Exception Handling

Throwing ExceptionsThrowing Exceptions

What if an exception is thrown and What if an exception is thrown and there is no catch block to match?there is no catch block to match?– System handles it (terminates program System handles it (terminates program

and prints stack)and prints stack)

Page 42: Chapter 15 – Exception Handling

15.4 finally clause15.4 finally clause

What if there is some code we want What if there is some code we want to execute regardless of exception or to execute regardless of exception or not?not?– finally finally block is usedblock is used

Page 43: Chapter 15 – Exception Handling

try{try{distance = Double.parseDouble(str);distance = Double.parseDouble(str);if (distance < 0){if (distance < 0){ throw new Exception("Negative distance is not throw new Exception("Negative distance is not

valid");valid");}}return distance;return distance;

} catch (NumberFormatException e){} catch (NumberFormatException e){System.out.println("'" + str + "'not valid System.out.println("'" + str + "'not valid

input, Please use digits only");input, Please use digits only");} catch (Exception e){} catch (Exception e){

System.out.println(e.getMessage());System.out.println(e.getMessage());} finally {} finally {

System.out.println(“Done”);System.out.println(“Done”);}}

Page 44: Chapter 15 – Exception Handling

Throwing ExceptionsThrowing Exceptions

finally is executed NO MATTER WHATfinally is executed NO MATTER WHAT

Even if there is a break or return in Even if there is a break or return in try blocktry block

Good for “cleanup” of a methodGood for “cleanup” of a method

Page 45: Chapter 15 – Exception Handling
Page 46: Chapter 15 – Exception Handling

Throwable

Exception

RuntimeException

IOException

NullPointerException

ArithmeticException

NegativeArrayIndexException

IndexOutOfBoundsException

IllegalArgumentException

ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

NumberFormatException

FileNotFoundException

EOFException

Exception Inheritance Hierarchy

Page 47: Chapter 15 – Exception Handling

try-catchtry-catch Control Flow Control Flow

code before try

try block

code after try

no exceptions occur

Page 48: Chapter 15 – Exception Handling

try-catchtry-catch Control Flow Control Flow

code before try

try block catch blockexception occurs

code after try

Page 49: Chapter 15 – Exception Handling

try-catchtry-catch Control Flow Control Flow

no exceptions occurred

try block

code after try

code before try

finally block (if it exists)

Page 50: Chapter 15 – Exception Handling

try-catchtry-catch Control Flow Control Flow

try blockexception occurs

code after try

code before try

finally block (if it exists)

catch block

Page 51: Chapter 15 – Exception Handling

try-catchtry-catch Control Flow Control Flow

no exceptions occurred

try block

exception occurs

code after try

code before try

finally block (if it exists)

matches firstcatch block?

matches nextcatch block?

true

false1st catch block

2nd catch block true

false

finally block (if it exists)

exception thrown to caller

Page 52: Chapter 15 – Exception Handling

Propagating ExceptionsPropagating Exceptions

When a method may throw an When a method may throw an exception, either directly or exception, either directly or indirectly, we call the method an indirectly, we call the method an exception throwerexception thrower..

Every exception thrower must be one Every exception thrower must be one of two types:of two types:– catcher.catcher.– propagator.propagator.

Page 53: Chapter 15 – Exception Handling

Propagating ExceptionsPropagating Exceptions

An An exception catcherexception catcher is an exception is an exception thrower that includes a matching thrower that includes a matching catchcatch block for the thrown exception.block for the thrown exception.

An An exception propagatorexception propagator does not contain does not contain a matching a matching catchcatch block. block.

A method may be a catcher of one A method may be a catcher of one exception and a propagator of another.exception and a propagator of another.

Page 54: Chapter 15 – Exception Handling
Page 55: Chapter 15 – Exception Handling

Propagating ExceptionsPropagating Exceptions

Do not catch an exception that is Do not catch an exception that is thrown as a result of violating a thrown as a result of violating a condition set by the client condition set by the client programmer (a precondition). programmer (a precondition).

Instead, propagate the exception Instead, propagate the exception back to the client programmer’s code back to the client programmer’s code and let him or her handle it.and let him or her handle it.