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
exampleCatchclass. - Line 4: We initialize the variable to store
value. - Line 5: The code throws an
exceptionand is enclosed with thetryblock. - Line 10: The
catchblock starts here. It catches theexception. - Line 11: We print the
exceptionthrown by the code.