When to use try and catch statement?

To guard against and handle a run-time error, enclose the code to monitor inside a try block.

Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.




public class Main {

  public static void main(String args[]) {

    try { // monitor a block of code.

      int d = 0;

      int a = 42 / d;

      System.out.println("This will not be printed.");

    } catch (ArithmeticException e) { // catch divide-by-zero error

      System.out.println("Division by zero.");


    System.out.println("After catch statement.");




The code above generates the following result.


devision By zeroo

After catch statement.