Java

Try Catch In Java

Java’s try-catch block is used to handle exceptions. The try block contains the code (or group of lines) that potentially raise an exception, and the associated catch block takes care of it if it does. We will look at a variety of examples in this manual to help us learn how to utilize try-catch in Java for exception management.

Try block in Java

The try block comprises a series of statements where an exception may occur, as was described at the beginning. If an exception occurs, the remaining statements in the try block are skipped, and the flow instantly shifts to the matching catch block. A try block is always followed by a catch block or finally block.

Note: Catch blocks, finally blocks, or both must come after a try block.

Syntax of try block with catch block

try{
   //statements that may cause an exception
}catch(Exception e){
  //statements that will execute when exception occurs
}

Syntax of try block with finally block

try{
   //statements that may cause an exception
}finally{
  //statements that execute whether the exception occurs or not
}

Syntax of try-catch-finally in Java

try{
   //statements that may cause an exception
}catch(Exception e){
  //statements that will execute if exception occurs
}finally{
  //statements that execute whether the exception occurs or not
}

Note: The decision of which statements to put within a try block is up to the programmer. A try block may be used to include statements in a program that the programmer believes may cause an exception, and catch blocks can be used to handle any possible exceptions.

Catch block in Java

The handling of exceptions is done in a catch block, which must come right after a try block. There may be numerous catch blocks connected to a single attempt block. Different exceptions may be caught in various catch blocks. The catch block for that specific exception is activated when an exception occurs in the try block. For instance, the commands included in the catch block for an arithmetic exception are executed if an arithmetic exception occurs in the try block.

Syntax of try catch in java

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}

Example: try catch in Java

The relevant catch block receives execution control if an exception occurs in the try block. You should arrange the catch blocks such that the generic exception handler catch block is at the end since, as was previously said, a single try block might have many catch blocks connected to it (see in the example below).

If you put the generic exception handler before all the catch blocks, it will show the general message even if it can handle all exceptions. Instead, you should put it towards the end. For every form of exception, you should always provide the user with a meaningful message rather than a general one.

class Example1 {
   public static void main(String args[]) {
      int num1, num2;
      try {
         /* We suspect that this block of statement can throw 
          * exception so we handled it by placing these statements
          * inside try and handled the exception in catch block
          */
         num1 = 0;
         num2 = 62 / num1;
         System.out.println(num2);
         System.out.println("Hey I'm at the end of try block");
      }
      catch (ArithmeticException e) { 
         /* This block will only execute if any Arithmetic exception 
          * occurs in try block
          */
         System.out.println("You should not divide a number by zero");
      }
      catch (Exception e) {
         /* This is a generic Exception handler which means it can handle
          * all the exceptions. This will execute if the exception is not
          * handled by previous catch blocks.
          */
         System.out.println("Exception occurred");
      }
      System.out.println("I'm out of try-catch block in Java.");
   }
}

Output:

You should not divide a number by zero
I'm out of try-catch block in Java.

Multiple catch blocks in Java

Given that the sample we just saw has several catch blocks, let’s look at some guidelines for multiple catch blocks using examples. See catching multiple exceptions in java for a further explanation of this.

1. A single attempt block may have any number of catch blocks, as I described previously.

2. All exceptions may be handled using a general catch block. This handles all exceptions, including ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException, and others. You may refer to this article: Exception Handling sample programs to view examples of NullPointerException and ArrayIndexOutOfBoundsException.

catch(Exception e){
  //This catch block catches all the exceptions
}

3. The catch blocks are entirely disregarded if there is no exception in the try block.

4. For that particular kind of exception, corresponding catch blocks are put into action:
A catch block that may manage ArithmeticException is catch(ArithmeticException e).
A catch block that may manage NullPointerException is catch(NullPointerException e).

5. Additionally, you may throw exceptions, which is a more complex issue that I have covered in separate lectures on user defined exception, the throws keyword, and throw vs. throws.

Example of Multiple catch blocks

class Example2{
   public static void main(String args[]){
     try{
         int a[]=new int[7];
         a[4]=30/0;
         System.out.println("First print statement in try block");
     }
     catch(ArithmeticException e){
        System.out.println("Warning: ArithmeticException");
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Warning: ArrayIndexOutOfBoundsException");
     }
     catch(Exception e){
        System.out.println("Warning: Some Other exception");
     }
   System.out.println("Out of try-catch block...");
  }
}

Output:

Warning: ArithmeticException
Out of try-catch block...

When an exception occurs in the try block, the several catch blocks in the aforementioned example are successively executed. This implies that if you position the last catch block (catch(Exception e)) immediately behind the try block, any exception will cause this block to run since it can handle all exceptions. To prevent such occurrences, this catch block should be put in last.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button