exception handling
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/nvrajasekharTRANSCRIPT
Exception Exception HandlingHandling
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
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?
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
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
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
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…
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.
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
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)
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
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
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
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
ProblemProblempublic class BankAccountpublic class BankAccount
{{
public void withdraw(double public void withdraw(double amountamount))
{{
if (if (amountamount > > balancebalance))
{{
??????????????????
}}
balance = balance - amount;balance = balance - amount;
} }
. . .. . .
} }
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;
} }
. . .. . .
} }
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;
} }
. . .. . .
} }
Throwing Exceptions: Throwing Exceptions: SyntaxSyntax
throw throw exceptionObjectexceptionObject; ;
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
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
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.
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
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
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);. . .. . .
}}
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
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
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?
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
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
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>}…}…
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");
} }
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
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
Catching ExceptionsCatching Exceptions
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?)
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());
}}
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();
}}
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;
}
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
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)
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" );
}}
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" ); }
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)
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
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”);}}
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
Throwable
Exception
RuntimeException
IOException
NullPointerException
ArithmeticException
NegativeArrayIndexException
IndexOutOfBoundsException
IllegalArgumentException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NumberFormatException
FileNotFoundException
EOFException
Exception Inheritance Hierarchy
try-catchtry-catch Control Flow Control Flow
code before try
try block
code after try
no exceptions occur
try-catchtry-catch Control Flow Control Flow
code before try
try block catch blockexception occurs
code after try
try-catchtry-catch Control Flow Control Flow
code before try
try block
code after try
no exceptions occur
catch blockexception occurs
try-catchtry-catch Control Flow Control Flow
no exceptions occurred
try block
code after try
code before try
finally block (if it exists)
try-catchtry-catch Control Flow Control Flow
try blockexception occurs
code after try
code before try
finally block (if it exists)
catch block
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
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.
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.
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.
ExampleExample
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 { ......}}
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..
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.
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