+ All Categories
Home > Technology > Exception handling

Exception handling

Date post: 04-Sep-2014
Category:
Upload: raja-sekhar
View: 15 times
Download: 0 times
Share this document with a friend
Description:
JAVA EXCEPTION HANDLING N.V.Raja Sekhar Reddy www.technolamp.co.in Want more interesting... Watch and Like us @ https://www.facebook.com/Technolamp.co.in subscribe videos @ http://www.youtube.com/user/nvrajasekhar
Popular Tags:
63
Exception Exception Handling Handling
Transcript
Page 1: Exception handling

Exception Exception HandlingHandling

Page 2: 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)

Throwing ExceptionsThrowing Exceptions

Page 3: Exception handling

Good programsGood programs

Need a robust program, reliable in Need a robust program, reliable in the eyes of a novice userthe eyes of a novice user

It should not (“cannot”) crash easily It should not (“cannot”) crash easily - what if Word always crashed when - what if Word always crashed when you hit the control key?you hit the control key?

Page 4: Exception handling

Good ProgramsGood Programs

How do we ensure a How do we ensure a robustrobust program? program? Option 1 – return a special value to Option 1 – return a special value to

determine if the method succeeded or determine if the method succeeded or failedfailed Ex. Make Ex. Make withdrawwithdraw return return truetrue or or falsefalse

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 doCalling method may not know what to do

Page 5: Exception handling

Good ProgramsGood Programs

Option 2 - Use exceptionsOption 2 - Use exceptions ExceptionException – an error condition that – an error condition that

can occur during the normal course can occur during the normal course of a program executionof a program execution

Exception handlingException handling is another is another form of control structure (like ifs and form of control structure (like ifs and switch statements)switch statements) When an error is encountered, the When an error is encountered, the

normal flow of the program is stopped normal flow of the program is stopped and the exception is handledand the exception is handled

Page 6: Exception handling

ExceptionsExceptions

We say an exception is We say an exception is thrownthrown when when it occursit occurs

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

Examples:Examples: Dividing by zeroDividing by zero Accessing a null objectAccessing a null object

Page 7: Exception handling

ExceptionsExceptions 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 normal execution stops and exception

handling beginshandling begins

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: Exception handling

ExceptionsExceptions Why use exceptions?Why use exceptions? consistencyconsistency (everyone else does it) (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 programmer can decide how to fix

problems.problems.

simplicitysimplicity Easy to pinpoint problems.Easy to pinpoint problems.

Page 9: Exception handling

Handling ExceptionsHandling Exceptions

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

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

them decide what to dothem decide 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 10: Exception handling

Handling ExceptionsHandling Exceptions

So far, we have let the system handle So far, we have let the system handle exceptionsexceptions

int score = in.nextInt();int score = in.nextInt();

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

Exception in thread "main" java.util.InputMismatchExceptionException in thread "main" java.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 11: Exception handling

Handling ExceptionsHandling Exceptions

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 Thrown because a StringString cannot be 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 12: Exception handling

Handling ExceptionsHandling Exceptions

Better solution: Instead of letting the Better solution: Instead of letting the program crash, use program crash, use Exception Exception HandlingHandling to improve program’s to improve program’s robustnessrobustness Exceptions cannot be ignoredExceptions cannot be ignored Exceptions are handled by Exception Exceptions are handled by Exception

Handlers directlyHandlers directly

Page 13: 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 14: 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 : illegal

parameter valueparameter value

Page 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 16: 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 exceeds balance");balance");

throw throw exceptionexception;;

}}

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

} }

. . .. . .

} }

Page 17: 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 18: Exception handling

Throwing Exceptions: Throwing Exceptions: SyntaxSyntax

throw throw exceptionObjectexceptionObject; ;

Page 19: Exception handling

Checked/Unchecked 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 These errors are due to external These errors are due to external

circumstances that the programmer circumstances that the programmer cannot prevent cannot prevent

Majority occur when dealing with input Majority occur when dealing with input and output and output

For example, For example, IOExceptionIOException

Page 20: Exception handling

Checked/Unchecked Checked/Unchecked ExceptionsExceptions

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:

NumberFormatExceptionNumberFormatException IllegalArgumentExceptionIllegalArgumentException NullPointerException NullPointerException

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

Can’t do anything about these Can’t do anything about these catastrophic problems, so don’t deal with catastrophic problems, so don’t deal with itit

Page 21: Exception handling
Page 22: Exception handling

Checked/Unchecked Checked/Unchecked ExceptionsExceptions

Unchecked Exceptions result from Unchecked Exceptions result from deficiencies in your code, so should deficiencies in your code, so should check on owncheck on 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, Problems with the file format, user input,

etc.etc.

Page 23: Exception handling

Checked/Unchecked Checked/Unchecked ExceptionsExceptions

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: Exception handling

Checked/Unchecked Checked/Unchecked ExceptionsExceptions

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: Exception handling

Handling Checked Handling Checked ExceptionsExceptions

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: Exception handling

Handling Checked Handling Checked ExceptionsExceptions

throwsthrows tells the compiler to “pass the buck” tells the compiler to “pass the buck” to the method that called this methodto the 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 hierarchyCan also group using hierarchy If method can throw an If method can throw an IOExceptionIOException and and FileNotFoundExceptionFileNotFoundException, only use , only use IOExceptionIOException

Page 27: Exception handling

Handling Checked Handling Checked ExceptionsExceptions

Why propagate when we could Why propagate when we could handle the error ourselves?handle the error ourselves? We may not know how toWe may not know how to Let user of my code decideLet user of my code decide

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

Page 28: Exception handling

Catching ExceptionsCatching 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 errors sophistication – cannot just allow errors to kill programto 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: Exception handling

Catching ExceptionsCatching Exceptions

To deal with this problem, install To deal with this problem, install exception handlers in your code to exception handlers in your code to deal with possible exceptionsdeal with possible exceptions

Handlers are try/catch statementsHandlers are try/catch statements

Page 30: 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: 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: Exception handling

trytry

{{

String filename = . . .; String filename = . . .;

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: Exception handling

ExampleExample

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: Exception handling

Catching ExceptionsCatching Exceptions

If there are no errors, the catch If there are no errors, the catch block is block is skippedskipped

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

Page 35: Exception handling

Catching ExceptionsCatching Exceptions

Page 36: Exception handling

Exception InformationException Information

Why do we have Exception objects?Why do we have Exception objects? We can get information on where the We can get information on where the

error happened and what exactly error happened and what exactly happenedhappened

Exception objects have 2 methods Exception objects have 2 methods defined: defined: getMessage() (what happened?)getMessage() (what happened?) printStackTrace() (where did it happen?)printStackTrace() (where did it happen?)

Page 37: Exception handling

getMessagegetMessage

Returns the data that cause the Returns the data that cause the errorerror Example:Example:

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

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

}}

Page 38: Exception handling

printStackTraceprintStackTrace

Prints out a trace of methods that Prints out a trace of methods that caused the error starting at the root caused the error starting at the root of the errorof the 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. This is what the system does when an This is what the system does when an

exception is thrownexception is thrown Example:Example:

……}catch(NumberFormatException e){}catch(NumberFormatException e){e.printStackTrace();e.printStackTrace();

}}

Page 39: 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();

}

Catching ALL ExceptionsCatching ALL Exceptions

trytry

{{

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

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

}

Page 40: Exception handling

Catching ALL ExceptionsCatching ALL Exceptions

Why is this probably a bad idea?Why is this probably a bad idea?

Probably want to handle each type of Probably want to handle each type of exception differentlyexception differently

Don't want to catch things like Don't want to catch things like NullPointerExeptionNullPointerExeption

Page 41: Exception handling

Catching ExceptionsCatching Exceptions

IMPORTANT! Order of catch blocks IMPORTANT! Order of catch blocks mattersmatters} 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 NumberFormatExceptionNumberFormatException is a specific type of the is a specific type of the

class class ExceptionException (inheritance) (inheritance)

Page 42: Exception handling

DemoDemop.s.v. main( String [] args ) p.s.v. main( String [] args ) {{

try {try { String filename = args[0], input;String filename = args[0], input; scanner = new Scanner( new File(filename) );scanner = new Scanner( new File(filename) ); input = scanner.nextLine();input = scanner.nextLine(); int value = Integer.parseInt( input );int value = Integer.parseInt( input ); double reciprocal = 1.0 / value;double reciprocal = 1.0 / value;

System.out.println( "rec=" + rec );System.out.println( "rec=" + rec );

} } catch ( Exception e ) catch ( Exception e ) { {

S.o.pln( "Found Exception: " + e );S.o.pln( "Found Exception: " + e );}} S.o.pln( "Done" );S.o.pln( "Done" );

}}

Page 43: Exception handling

String filename=args[0], input;String filename=args[0], input;try {try {

scanner = new Scanner(new File(filename));scanner = new Scanner(new File(filename)); input = scanner.nextLine();input = scanner.nextLine(); int value = Integer.parseInt( input );int value = Integer.parseInt( input ); double reciprocal = 1.0 / value;double reciprocal = 1.0 / value; System.out.println( "rec=" + rec );System.out.println( "rec=" + rec );

}}catch ( NumberFormatException e ) {catch ( NumberFormatException e ) {S.o.pln( input + " is not an integer");S.o.pln( input + " is not an integer");

}}catch ( ArithmeticException e ) { catch ( ArithmeticException e ) {

S.o.pln( "Can't divide by zero" );S.o.pln( "Can't divide by zero" );}}catch ( FileNotFoundException e ) { catch ( FileNotFoundException e ) {

S.o.pln( filename + " Not Found" );S.o.pln( filename + " Not Found" );}}finally { S.o.pln( "Done" ); }finally { S.o.pln( "Done" ); }

Page 44: Exception handling

Catching ExceptionsCatching 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? The system handles it (terminates The system handles it (terminates

program and prints the stack trace)program and prints the stack trace)

Page 45: Exception handling

The finally clauseThe finally clause

Recall that whenever an exception Recall that whenever an exception occurs, we immediately go to the occurs, we immediately go to the catch blockcatch block

What if there is some code we want What if there is some code we want to execute regardless of whether to execute regardless of whether there was an exception?there was an exception? finally finally block is usedblock is used

Page 46: Exception handling

The finally clauseThe finally clausetry{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 } 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");} catch} catch (Exception e){ (Exception e){

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

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

Page 47: Exception handling

The finally clauseThe finally clause

finally is executed finally is executed NO MATTER NO MATTER WHATWHAT

Even if there is a break or return in Even if there is a break or return in the try blockthe try block

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

Page 48: Exception handling
Page 49: Exception handling

Throwable

Exception

RuntimeException

IOException

NullPointerException

ArithmeticException

NegativeArrayIndexException

IndexOutOfBoundsException

IllegalArgumentException

ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

NumberFormatException

FileNotFoundException

EOFException

Exception Inheritance Hierarchy

Page 50: Exception handling

try-catchtry-catch Control Flow Control Flow

code before try

try block

code after try

no exceptions occur

Page 51: Exception handling

try-catchtry-catch Control Flow Control Flow

code before try

try block catch blockexception occurs

code after try

Page 52: Exception handling

try-catchtry-catch Control Flow Control Flow

code before try

try block

code after try

no exceptions occur

catch blockexception occurs

Page 53: 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 54: 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 55: 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

Page 56: 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 Every exception thrower must be one of two types:one of two types: a catcher, ora catcher, or a propagator.a propagator.

Page 57: 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 does not contain a matching contain 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 58: Exception handling

ExampleExample

The following figure shows a sequence of The following figure shows a sequence of method calls among the exception throwers. method calls among the exception throwers.

Method D throws an instance of Method D throws an instance of ExceptionException. . The green arrows indicate the direction of The green arrows indicate the direction of calls. The red arrows show the reversing of calls. The red arrows show the reversing of call sequence, looking for a matching call sequence, looking for a matching catcher. Method B is the catcher. catcher. Method B is the catcher.

The call sequence is traced by using a stack.The call sequence is traced by using a stack.

Page 59: Exception handling

ExampleExample

Page 60: Exception handling

Propagating ExceptionsPropagating Exceptions

If a method is an exception propagator, we If a method is an exception propagator, we need to modify its header to declare the need to modify its header to declare the type of exceptions the method propagates.type of exceptions the method propagates.

We use the reserved word We use the reserved word throwsthrows for this for this declaration.declaration.

public void C( ) throws Exception {public void C( ) throws Exception { ......}}public void D( ) throws Exception {public void D( ) throws Exception { ......}}

Page 61: Exception handling

Propagating ExceptionsPropagating Exceptions

Without the required Without the required throws throws ExceptionException clause, the program will clause, the program will not compile.not compile.

However, for exceptions of the type However, for exceptions of the type called called runtime exceptionsruntime exceptions, the , the throwsthrows clause is clause is optionaloptional..

Page 62: Exception handling

Propagating vs. CatchingPropagating vs. Catching

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. programmer.

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

Page 63: Exception handling

Exceptions in a Exceptions in a ConstructorConstructor

We can thrown an exception in the We can thrown an exception in the constructor if a condition is violatedconstructor if a condition is violated For example, we may throw an For example, we may throw an IllegalArgumentExceptionIllegalArgumentException if a parameter if a parameter value is invalidvalue is invalid


Recommended