try and catch block in Java

When your program performs an operation that generates an exception, an exception will be thrown. You can catch that exception and handle it with the help of try and catch blocks.

try block in Java

  • In try block, we place the line of codes that may cause an exception.
  • A try block must be followed by a catch block or a finally block.

catch block in Java

  • The catch block is used to write the code that handles the exception.
  • A catch block is only executed if it catches the exception coming from the try block.
  • If no exception is generated from the try block, then all the catch blocks are skipped.

Different forms of try, catch and finally block

Type-I
try{
	//code that may generate exception.	
}catch(ExceptionClass obj){
	//code to handle the exception.
}
Type-II
try{
	//code that may generate exception.	
}finally{
	//cleanup code
}
Type-III
try{
	//code that may generate exception.	
}catch(ExceptionClass obj){
	//code to handle the exception.
}finally{
	//cleanup code
}
Type-IV
try{
	//code that may generate exception.	
}catch(ExceptionClass1 obj){
	//code to handle the exception.
}catch(ExceptionClass2 obj){
	//code to handle the exception.
}
...
catch(ExceptionClassn obj){
	//code to handle the exception.
}
Type-V
try{
	//code that may generate exception.	
}catch(ExceptionClass1 obj){
	//code to handle the exception.
}catch(ExceptionClass2 obj){
	//code to handle the exception.
}
...
catch(ExceptionClassn obj){
	//code to handle the exception.
}finally{
	//cleanup code
}

Example of try-catch block

public class Exceptionhandling
{
	public static void main(String args)
	{
		int a = 20;
		int b = 0;
		try
		{
			System.out.println("Result = " + a/b);
		}
		catch(ArithmeticException ae)
		{
				System.out.println(ae);
		}
		System.out.println("Remaining code...");
	}
}

Output

Exception in thread main java.lang.ArithmeticException:/ by zero
Remaining code...	

Multiple catch block in Java

A try can have multiple catch block. The catch block that catches the exception is executed while all others are skipped. If no exception arises from the try block, all the catch blocks are skipped.

Refer type-iv, and type-v mentioned above to know the syntax of multiple catch block.

class MultiCatch
{
	public static void main(String args[])
	{
		try
		{						
			int arr[] = new int[3];
			arr[3] = 123;
		}
		catch(ArithmeticException e)
		{
			System.out.println(e);
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println(e);
		}
		finally
		{
			System.out.println("finally");
		}
	}
}

Note - In multiple catch block alway catch the derived class exception and then the super class exception. If you don't perform this operation, you will get compile time error.

Example

class ExceptionHandling
{
	public static void main(String args[])
	{
		try
		{
			int a[] = new int[3];
			a[4] = 30;	
		}
		catch(IndexOutOfBoundsException i){
			System.out.println(i);
		}
		catch(ArrayIndexOutOfBoundsException ai){
			System.out.println(ai);
		}
	}
}

Output

error: exception ArrayIndexOutOfBoundsException has already been caught
catch(ArrayIndexOutOfBoundsException ai){

Here, you can see ArrayIndexOutOfBoundsException is a derived class of IndexOutOfBoundsException. Just because of this, we are getting compile time error. To resolve it, simply interchange their position.

Nested try block in Java

try block that contains more than one try block is known as nested try block.

Syntax

try
{
	expression 1;
	expression 2;
	try
	{
		expression 1;
		expression 2;
	}
	catch(Exception e)
	{
		//code to handle exception
	}
}
catch(exception e)
{
	//code to handle exception	
}
.....

Example of nested try block

class ExceptionHandling
{
   public static void main(String args[])
   {
      int a = 20;
      int b = 0;
      try
      {
         try
         {
            System.out.println("Result = " + a/b);  
         }catch(ArithmeticException e){
            System.out.println(e);
         }
         try
         {
            int a[] = new int[3];
	    a[3] = 14;
    	 }catch(ArrayIndexOutOfBoundsException e)
    	 {
            System.out.println(e);
    	 }
    	 System.out.println("Remaining code...");  
      }catch(Exception e){
         System.out.println("handled");
      }
      System.out.println("normal flow..");  
   }
}