Using try and catch


Although the default exception handler provided by the Java run-time system is effective for debugging, you will usually want to handle an exception yourself. There are two benefits to doing this.

Most users will be confused if you stop running your program and print a stack trace whenever an error occurs! Fortunately, it is quite easy to prevent.

To prevent and manage run-time errors, simply turn off the code you want to monitor within a try block. Immediately following the try block, include a catch clause that specifies the type of exception you want to catch. How to do it easily, For example, the following program includes a try block and a catch clause that processes arithmetic exceptions generated by section-by-zero errors:

Program
public class Main {
  public static void main(String[] args) {
    int a,b;
    try{ // monitor a block of code
     a = 0;
     b = 12/a;
     System.out.println("This will be not printed.");
    }
    catch(ArithmeticException e){ // catch divide-by-zero error
     System.out.println("Division by zero exception");
    }
    System.out.println("After catch statement");
  }
}

Notice that the println() method inside the try block did not run because the code of the try block where the exception occurs will not execute the code of the next line. In the example above, with the exception of line 2 of the try block, the code of the catch block is run and the next normal codes are run.

A try and its catch statement combine to form a unit. The scope of the catch clause is limited to the statements specified by the immediate previous try statement. A catch statement cannot hold exceptions thrown by another try statement. The statement protected by try must be surrounded by curly braces. You cannot use try in a single statement.

The goal of most specific catch clauses is to resolve the exceptional condition and then continue as if the error never occurred. For example, in the next program, each repetition of the loop obtains two random integers. Those two integers are divided by each other, and the result is used to divide the value 1234. The final result is put into x. if either division operation causes a divide-by-zero error, it is caught, the value of x is set to zero, and the program continues.

Program
import java.util.Random;
public class Main {
  public static void main(String[] args) {
    int x=0,y=0,z=0;
    Random r=new Random();
    for(int i=0;i<2000;i++)
    {
     try{
      y = r.nextInt();
      z = r.nextInt();
      x = 1234/(y/z);
     }
     catch(ArithmeticException e){
      System.out.println("Division by zero.");
      x=0; // set a to zero and continue
     }
     System.out.println("x: " + x);
    }
  }
}