Exception Handling in Java
Exception Handling in Java
in Java
An object of
exception class exception
Int data=10/0; is thrown object
No Is Yes
handled
?
JVM
1)Prints out exception Rest of the code is
description executed
2) Prints the stack trace
3) Terminate the program
Try-catch Block
try{
//statements that may cause an
exception
}
catch (exception(type)
e(object))
{
//error handling code
}
Multiple catch
try { //Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
……
Sequence of Events
Preceding step
try block
statement
unmatched catch
matching catch
unmatched catch
next step
class Example2{
public static void main(String args[]){
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:ArrayIndexOutOfBoundsException"
); }
catch(Exception e){
Nested try catch
• One try-catch block can be present in the another
try’s body. This is called Nesting of try
catch blocks.
• Each time a try block does not have a catch
handler for a particular exception, the stack is
unwound and the next try block’s catch (i.e.,
parent try block’s catch) handlers are inspected
for a match.
• If no catch block matches, then the java run-time
system will handle the exception.
• Syntax of Nested try Catch
try
{ statement 1;
try {
statement 2; }
catch(Exception e1) {
//Exception Message }
}
catch(Exception e2) //Catch of Main(parent) try block
{ //Exception Message
}
What is Finally Block
• A finally statement must be associated with
a try statement.
no Exception Yes
Occurred ?
no Yes
Exception
Handled ?
Preceding step
try block
statement
unmatched catch
matching catch
unmatched catch
finally
next step
class Simple{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{