What is the catch keyword in java?

In this Answer, we’ll learn about the catch keyword in Java. The catch keyword is used to receive or catch and handle the exceptions that are thrown by the try block.

The catch block instructs the code on what should be executed when an exception throws. We can write multiple catch blocks for one try block. The thrown exception must be a parent class of all exceptions, or we can also specify exceptions thrown on our own.

Syntax

catch
{
    // The code block which handle exception thrown by try block
}

Code example

Lets' look at the code below:

class exampleCatch {
public static void main(String[] args)
{
int a = 10, b = 0, total;
try {
total = a / b;
System.out.println("result" + total);
}
catch (ArithmeticException e) {
System.out.println("Exception : The code throw the exception,and handled with catch block");
}
}
}

Code explanation

  • Line 1: We create the exampleCatch class.
  • Line 4: We initialize the variable to store value.
  • Line 5: The code throws an exception and is enclosed with the try block.
  • Line 10: The catch block starts here. It catches the exception.
  • Line 11: We print the exception thrown by the code.