Java try-catch statement

Using Try Catch Statements

Although the Java run-time system’s default exception handler is handy for debugging, you’ll normally want to handle an exception yourself. There are two advantages to doing so. It first enables you to correct the mistake. Second, it stops the program from quitting on its own.

Syntax of try..catch block

try{
    //code that might cause an exception
}
catch(Exception obj){
    //handling the exception
}

Typically, we write the code that raises exceptions in the try block, and if exceptions are caught then, control of the program is transferred to the catch block.

Let us understand the working of try..catch by using an example.

Code:

Java Code

import java.util.Scanner;
class Division {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int a, b, c;
    System.out.println("Enter two numbers");
    a = input.nextInt();
    b = input.nextInt();
    try {
      c = a / b;
      System.out.println("Result: " + c);
    } catch (ArithmeticException e) {
      System.out.println("Please enter a valid number");
    }

  }
}

In the above example whenever the user types 0 as input an exception is raised, when an exception is raised it is caught by the catch block and prompts the user to enter the valid input. If the user has entered a valid number then the result will be printed on the console.

Multiple Catch Blocks

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. 

Code:

Java Code

class MultipleCatch {
  public static void main(String args[]) {
    try {
      int a = args.length;
      System.out.println("a = " + a);
      int b = 21 / a;
      int c[] = {10};
      c[44] = 99;
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index oob: " + e);
    }
    System.out.println("After try/catch blocks.");
  }
}

Explanation: When the user enters zero as input then it will cause ArithmeticException, and if the user enters a value greater than zero then also it will cause an error. As We just have array c of length 1 but we are trying to assign index 44 to 99.

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.

Code:

Java Code

class NestedTryCatch {
  public static void main(String args[]) {
    try {
      int n = args.length;
      /* If no command-line args are present,
      the following statement will generate
      a divide-by-zero exception. */
      int b = 42 / n;
      System.out.println("n = " + n);
      try { // nested try block
        /* If one command-line arg is used,
        then a divide-by-zero exception
        will be generated by the following code. */
        if (n == 1) 
        n = n / (n - n); // division by zero
        /* If two command-line args are used,
        then generate an out-of-bounds exception. */
        if (n == 2) {
          int c[] = { 1 };
          c[42] = 99; // generate an out-of-bounds exception
        }
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index out-of-bounds: " + e);
      }
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    }
  }
}

Special thanks to P.C.Bhuvaneshwari for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article