Module3 Java ExceptionHandling Jenila
Module3 Java ExceptionHandling Jenila
If an exception occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed.
}
catch (Exception Type1 exob) {
// exception handler for Exception Type1
}
catch (Exception Type1 exob) {
// exception handler for Exception Type1
}
// …
finally {
// block of code to be executed before try block ends
}
Code without exception handling
public class JavaExceptionExample{
public static void main(String args[]){
int data=100/0;
int A=10, B=5;
System.out.println(A+B);
System.out.println("Code successfully executed");
}
}
}
Dr. L.M. Jenila Livingston 14
public class MultipleCatchBlock2 { Example 3: Multiple catch
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Dr. L.M. Jenila Livingston 15
//main try block
try { Nested try
statement 1;
statement 2;
//try catch block within another try block
try {
statement 3;
statement 4;
//try catch block within nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
} Dr. L.M. Jenila Livingston 16
Example 4: Nested try
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
try{
}
catch(error) {
expression; } // code for handling exception.
Method Description
printStackTrace() It print the name of the exception,
description and complete stack trace
including the line where exception occurred.
toString() It prints the name and description of the
exception.
getMessage() Mostly used. It prints the description of the
exception.
32
References
• https://www.javatpoint.com/exception-
handling-in-java
• https://www.tutorialspoint.com/java/java_exc
eptions.htm