Exception Handling
Exception Handling
}
Test it Now
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of
the code is not executed (in such case, the rest
of the code statement is not printed).
There might be 100 lines of code after the
exception. If the exception is not handled, all
the code below the exception won't be
executed.
Solution by exception handling
Let's see the solution of the above problem by
a java try-catch block.
Example 2
TryCatchExample2.java
public class TryCatchExample2 {
}
Test it Now
Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of
the code is executed, i.e., the rest of the
code statement is printed.
Example 3
In this example, we also kept the code in a try
block that will not throw an exception.
TryCatchExample3.java
public class TryCatchExample3 {
}
}
Test it Now
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in
the try block, the rest of the block code will
not execute.
Example 4
Here, we handle the exception using the parent
class exception.
TryCatchExample4.java
public class TryCatchExample4 {
}
Test it Now
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom
message on exception.
TryCatchExample5.java
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by z
ero");
}
}
}
Test it Now
Output:
Can't divided by zero
Example 6
Let's see an example to resolve the exception
in a catch block.
TryCatchExample6.java
public class TryCatchExample6 {
Test it Now
Output:
25
Example 7
In this example, along with try block, we also
enclose exception code in a catch block.
TryCatchExample7.java
public class TryCatchExample7 {
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch blo
ck
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
Test it Now
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't
contain the exception code. So, enclose
exception code within a try block and use
catch block only to handle the exceptions.
Example 8
In this example, we handle the generated
exception (Arithmetic Exception) with a
different type of exception class
(ArrayIndexOutOfBoundsException).
TryCatchExample8.java
public class TryCatchExample8 {
}
// try to handle the ArithmeticExceptio
n using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Test it Now
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Example 9
Let's see an example to handle another
unchecked exception.
TryCatchExample9.java
public class TryCatchExample9 {
}
Test it Now
Output:
java.lang.ArrayIndexOutOfBoundsException:
10
rest of the code
Java Catch Multiple Exceptions
Java Multi-catch block
A try block can be followed by one or more
catch blocks. Each catch block must contain a
different exception handler. So, if you have to
perform different tasks at the occurrence of
different exceptions, use java multi-catch
block.
Points to remember
At a time only one exception occurs and at a
time only one catch block is executed.
All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before catch
for Exception.
Flowchart of Multi-catch Block
Example 1
Let's see a simple example of java multi-catch
block.
MultipleCatchBlock1.java
public class MultipleCatchBlock1 {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Ex
ception occurs");
}
catch(ArrayIndexOutOfBoundsExce
ption e)
{
System.out.println("ArrayIndexOu
tOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Excepti
on occurs");
}
System.out.println("rest of the code")
;
}
}
Test it Now
Output:
Arithmetic Exception occurs
rest of the code
Example 2
MultipleCatchBlock2.java
public class MultipleCatchBlock2 {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Ex
ception occurs");
}
catch(ArrayIndexOutOfBoundsExce
ption e)
{
System.out.println("ArrayIndexOu
tOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Excepti
on occurs");
}
System.out.println("rest of the code")
;
}
}
Test it Now
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
In this example, try block contains two
exceptions. But at a time only one exception
occurs and its corresponding catch block is
executed.
MultipleCatchBlock3.java
public class MultipleCatchBlock3 {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Ex
ception occurs");
}
catch(ArrayIndexOutOfBoundsExce
ption e)
{
System.out.println("ArrayIndexOu
tOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Excepti
on occurs");
}
System.out.println("rest of the code")
;
}
}
Test it Now
Output:
Arithmetic Exception occurs
rest of the code
Example 4
In this example, we generate
NullPointerException, but didn't provide the
corresponding exception type. In such case,
the catch block containing the parent
exception class Exception will invoked.
MultipleCatchBlock4.java
public class MultipleCatchBlock4 {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Ex
ception occurs");
}
catch(ArrayIndexOutOfBoundsExce
ption e)
{
System.out.println("ArrayIndexOu
tOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Excepti
on occurs");
}
System.out.println("rest of the code")
;
}
}
Test it Now
Output:
Parent Exception occurs
rest of the code
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Java Nested try Example
Example 1
Let's see an example where we place a try
block within another try block for two
different exceptions.
NestedTryBlock.java
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);
}
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (
outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic ex
ception");
System.out.println(" inner try bloc
k 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exce
ption");
System.out.println("inner try block 1
");
}
}
// to handle ArrayIndexOutOfBoundsExc
eption
catch (ArrayIndexOutOfBoundsExceptio
n e4) {
System.out.print(e4);
System.out.println(" outer (main) try bl
ock");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main tr
y-block");
}
}
}
Output:
try {
System.out.println(e);
}
//executes regardless of exception occured
or not
finally {
System.out.println("finally block is alway
s executed");
}
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:
Example 3: Throwing Use
r-defined Exception
exception is everything else under the
Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exceptio
n
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exce
ption
throw new UserDefinedException("Thi
s is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the excepti
on");
// Print the message from MyException
object
System.out.println(ude.getMessage());
}
}
}
Output:
System.out.println("normal flow...");
}
}
Test it Now
Output:
exception handled
normal flow...
Case 2: Declare Exception
In case we declare the exception, if exception
does not occur, the code will be executed fine.
In case we declare the exception and the
exception occurs, it will be thrown at runtime
because throws does not handle the exception.
Let's see examples for both the scenario.
A) If exception does not occur
Testthrows3.java
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation perform
ed");
}
}
class Testthrows3{
public static void main(String args[])throws
IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Test it Now
Output:
device operation performed
normal flow...
B) If exception occurs
Testthrows4.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws
IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Test it Now
Output:
System.out.println(e);
}
// executes regardless of exception occurre
d or not
finally {
System.out.println("finally block is alway
s executed");
}
System.out.println("rest of the code...");
}
}
Output:
System.gc();
System.out.println("End of the garbage c
ollection");
}
// defining the finalize method
protected void finalize()
{
System.out.println("Called the finalize()
method");
}
}
Output: