Site icon JavaGoal

try and catch java block

In this post, we will learn how we can use the try and catch block in java. Let’s discuss the try-catch exception with an example.

Here is the table content of the article.
1. What is try and catch block?
2. The important thing about try-catch?
3. try block with multiple catches?

4. Multiple catch blocks in java?

What is try and catch block?

We place a try block on a set of statements where we except an exception. Place the code in a try block that might throw an exception. If an exception occurs in the try block, then the rest code doesn’t execute that placed in the same block. When an exception occurs in the try block then the control flow of the program directly jumps to either the catch block or finally block. The catch block is used to handle the occurred exceptions. To use the catch block you must declare the type of exception within the parameter. We will see it with an example.

The important thing about try and catch java

1. The try block must be followed by either catch or finally. So, you can’t use the try block solely. If you are placing, try block in your program then you must use either catch block or finally block.
2. The catch block always follows the try block.
3. You can’t place anything between the try and catch block. The catch block will be immediately placed by the try block.

try 
{
   // code that might throw an exception
} 
catch (ExceptionName ex)
{
   // Catch block
}

Example: Let’s take an example to better explain try and catch block. Suppose we have a class UseOfTryCatchBlock and we are performing some arithmetic operations. In this example, we have some code that might create an exception it’s our responsibility to place the code in the try block. In the catch block, we are declaring the exception type as a parameter.

public class UseOfTryCatchBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		int a = 2;
		int b = 0;
    	 	int c = a/b;  
		System.out.println("result of calculation = "+ c);  
  	 }
   	catch (ArithmeticException e)
  	{
                e.printStackTrace();
  	}  
  	 //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: This code is inside in the try block java.lang.ArithmeticException: / by zero at UseOfTryCatchBlock.main(UseOfTryCatchBlock.java:10) This code is outside from the try block

Explanation of Example: In this example, ArithmeticException occurred because the compiler tried to divide a number by zero(0). That exception is handled by catch block and printing the reason for the exception. The rest of the code works fine because that code is placed outside the try-catch block.

try block with multiple catches

A try block can be followed by multiple catch blocks. Each catch block contains different exception types in parameters. If you want to handle different types of exceptions and perform some different actions on the occurrence of an exception, then use try block with multiple catches.

try 
{
   // code that might throw an exception
} 
catch (ExceptionTypeA e) 
{
   // Perform some action for ExceptionTypeA
} 
catch (ExceptionTypeB e) 
{
   // Perform some action for ExceptionTypeB
}
.
.
.
catch (ExceptionTypeN e) 
{
   // Perform some action for ExceptionTypeN 
}

Example: Let’s take an example to explain try and multiple catch blocks.

public class UseOfTryAndMultipleCatchBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		int a = 2;
		int b = 0;
    	 	int c = a/b;  
		System.out.println("result of calculation = "+ c);  
  	 }
   	catch (ArithmeticException e)
  	{
       	e.printStackTrace();
		System.out.println("ArithmeticException are handled");  
  	}
	catch (NumberFormatException e)
  	{
       	e.printStackTrace();
		System.out.println("NumberFormatException are handled");  
  	}
	catch (Exception e)
  	{
       	e.printStackTrace();
		System.out.println("Exception are handled");  
  	}

  	 //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: This code is inside in the try block java.lang.ArithmeticException: / by zero ArithmeticException are handled This code is outside from the try block at UseOfTryAndMultipleCatchBlock.main(UseOfTryAndMultipleCatchBlock.java:10)

Explanation of example: In this example, we have multiple catch blocks with a single try block. We used different exception types in the different catch blocks. When the compiler executes the code of the try block it throws an exception that is caught by the catch block. The compiler executes only one block at a time. So, when we are trying to divide a number by zero the ArithmeticException occurs and only the ArithmeticException catch block will be executed.

public class MainClass 
{
    public static void main (String [] args) 
    {
    	try
    	{
    		int a = 2/0;
    	}
    	catch(Exception e)
    	{
    		System.out.println("Exception : Divide by Zero");
    	}
    	catch(ArithmeticException e)
    	{
    		System.out.println("ArithmeticException : Divide by Zero");
    	}
    	finally 
    	{
    		System.out.println("Finally");
    	}
    }
}

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception at MainClass.main(MainClass.java:13)

In the above example, it throws an exception because the catch block of the ArithmeticException is unreachable. The catch block with Exception already catches the exception because it is the superclass of ArithmeticException.

Multiple catch blocks in java

we have seen how to use the catch block with try and some examples. Now we will see how we can use Multiple catch blocks in java but there are some rules to use multiple catches:
Rule 1: The compiler executes only one exception at a time all other blocks will be skipped automatically as shown in the above example.
Rule 2: When we use Multiple catch block in java, All catch blocks must be placed in the least generic to most generic ordered i.e. catch for ArithmeticException and NumberFormatException must come before catching for Exception. Because ArithmeticException and NumberFormatException are least generic than Exception. If we place the most generic catch block first, then the compiler gives an error in compilation.

public class UseOfTryAndMultipleCatchBlock
{  
  public static void main (String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		int a = 2;
		int b = 0;
    	 	int c = a/b;  
		System.out.println("result of calculation = "+ c);  
  	}
	catch (Exception e)
  	{
       	e.printStackTrace();
		System.out.println("Exception are handled");  
  	}
   	catch (ArithmeticException e)
  	{
       	e.printStackTrace();
		System.out.println("ArithmeticException are handled");  
  	}
	catch (NumberFormatException e)
  	{
       	e.printStackTrace();
		System.out.println("NumberFormatException are handled");  
  	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: UseOfTryAndMultipleCatchBlock.java:18: error: exception ArithmeticException has already been caught catch (ArithmeticException e) UseOfTryAndMultipleCatchBlock.java:23: error: exception NumberFormatException has already been caught catch (NumberFormatException e)

Explanation of example: This is because we placed the generic exception catch block (Exception) in the first place which means all other catch blocks (ArithmeticException & NumberFormatException) placed after this block are unreachable. You should always place the most generic block at the end of all other specific exception catch blocks.

If you place a generic block at first, then the compiler will never be able to reach any other block. Because a generic catch block (Exception)can handle all the exceptions. Whether it is ArithmeticException or NumberFormatException or any other type of exception. An exception is super most class so it can handle all the subclass exceptions.

Exit mobile version