Exception Handling Tutorials in Java

0
123
Spread the love
  • 59
  • 85
  • 26
  • 89
  •  
  •  
  •  
  • 14
  •  
  •  
    273
    Shares

It is not like Switch statement where we need to break to prevent remaining Exceptions from Executing.Once the catch clause executes the code,the control comes out of the whole try catch block.

Inside try block , there can be many methods or statements generate the same Exception,in that case one handler is enough to catch it.

While hunting for proper Catch clause the JVM follows the below:

  1. The clause’s parameter type is the same as the type of the exception that was thrown.
  2. The clause’s parameter type is a super class of the Exception type.

syntax for try catch in exception in java tutorial.Guide on exception handling in java with examples. This portion is very important for exception in java interview questions.

Single catch:


try{
statements that cause exception or Exception object creator
} 
catch(Exception_type obj)
{ 
statements that handles the exception or Exception handler
} 

real time example:

It is very important to understand a real time example (exception in java tutorial) or exception handling in java with examples


public class myException{
public static void main(String []args){
myFunction(2,2);
myFunction(2,0);
myFunction(4,2);
}
private static void myFunction(int x,int y){
int z=0;
try{
z=(int)x/y;
}
catch(ArithmeticException e)
{
System.out.println("Can not divide by zero!!");
}
System.out.println("result of division"+z);
}
}

The output of the code:
$javac myException.java
$java -Xmx128M -Xms16M myException
case-1
result of division1
case-2
Can not divide by zero!!
result of division0
case-3
result of division2

Also we have one keyword called finally which takes care of the recovery or post exceptional steps:

try catch and finally block:


try{
statements that cause exception or Exception object creator
} 
catch(Exception_type obj)
{
statements that handles the exception or Exception handler
}
finally
{ 
//recovery code or post exception steps 
} 

Multiple catch statements:

Exception in java tutorial is not completed without this section. This is required when real time we may deal with different exceptions.When an exception is thrown , the exception handler looks through the nearest handler in order they are written to find a proper match.

If the handler gets a perfect match the catch block is executed, ignoring the remaining catch blocks.Lets see exception handling in java with examples.Very important aspect for exception in java interview questions.


try{
statements that cause exception or Exception object creator
} 
catch(Exception_type1 obj)
{
statements that handles the exception or Exception handler
}
catch(Exception_type2 obj)
{
statements that handles the exception or Exception handler
}
catch(Exception_type3 obj)
{
statements that handles the exception or Exception handler
}
....
....
....
catch(Exception_typeN obj)
{
statements that handles the exception or Exception handler
}
finally
{ 
//recovery code or post exception steps 
} 

real time example:

Lets see one more exception handling in java with examples and exception handling in java best practices


public class myMultiCatchException{
    static String a[]={"Hello","Java"};
    static String myString=null; 
    public static void main(String []args){
    try{
    if(a[2].equals("hi"))
   //can change to a[0] to test the second condition 
    System.out.println("hi");
    if (myString.equals("hello"))
    System.out.println("true");
}
catch(NullPointerException e)
{
System.out.println("A null pointer exception is found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("index out of bound");
}
}
}

The output of the code:
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
index out of bound
if we change to a[2] to a[0]
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
A null pointer exception is found
lets see exception handling in java with examples with one more example:


public class myMultiCatchException{
   public static int j;
   public static void main(String args[])
   {
       for(int i=0;i<4;i++)
       {
           try{
               switch(i){
                   case 0:
                       int zero=0;
                       j=2/zero;
                       //divide by zero exception
                       break;
                    case 1:
                        int b[]=null;
                        j=b[0];
                        //null pointer exception
                        break;
                    case 2:
                        int[] c=new int[2];
                        j=c[10];
                        //array outofBoundException
                        break;
                    case 3:
                        char ch="java".charAt(10);
                        //String index out of bounds Exception
                        break;
               }
           }
catch(ArithmeticException e)
{
System.out.println("can not divide by zero");
}
catch(NullPointerException e)
{
System.out.println("A null pointer exception has occured");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bound");
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("String index is out of bound");
}
}
}
}

The output of the code:
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
can not divide by zero
A null pointer exception has occured
Array index is out of bound
String index is out of bound

While working with multiple catch statement,we need to be careful the order of the Exception class.

In case , in the catch statement if a higher (placed higher in the Exception hierarchy) order exception is mentioned before a lower(placed lower in the Exception hierarchy ) order,then the java runtime picks up the higher exception as it has been placed higher in the catch statement or as it appears first.

The lower order is ignored.It produces the unreachable code or an error.Lets see exception handling in java with examples


public class myMultiCatchException{
   public static int j;
   public static void main(String args[])
   {
       for(int i=0;i<4;i++)
       {
           try{
               switch(i){
                   case 0:
                       int zero=0;
                       j=2/zero;
                       //divide by zero exception
                       break;
                    case 1:
                        int b[]=null;
                        j=b[0];
                        //null pointer exception
                        break;
                    case 2:
                        int[] c=new int[2];
                        j=c[10];
                        //array outofBoundException
                        break;
                    case 3:
                        char ch="java".charAt(10);
                        //String index out of bounds Exception
                        break;
               }
           }
           catch(Exception e)
           {
               System.out.println("An error has occured");
           }
catch(ArithmeticException e)
{
System.out.println("can not divide by zero");
}
catch(NullPointerException e)
{
System.out.println("A null pointer exception has occured");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bound");
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("String index is out of bound");
}
}
}
}

See here the Exception the super class is mentioned first in the catch block.

As it is placed in the higher in the exception hierarchy the java runtime will always refer to the Exception class even though specific lower order (placed lower in the exception hierarchy).

As a result we get errors:
output of the code:
$javac myMultiCatchException.java
myMultiCatchException.java:35: error: exception ArithmeticException has already been caught
catch(ArithmeticException e)
^
myMultiCatchException.java:39: error: exception NullPointerException has already been caught
catch(NullPointerException e)
^
myMultiCatchException.java:43: error: exception ArrayIndexOutOfBoundsException has already been caught
catch(ArrayIndexOutOfBoundsException e)
^
myMultiCatchException.java:47: error: exception StringIndexOutOfBoundsException has already been caught
catch(StringIndexOutOfBoundsException e)
^
4 errors

Catch multiple exceptions with single catch statements:

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 59
  • 85
  • 26
  • 89
  •  
  •  
  •  
  • 14
  •  
  •  
    273
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here