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.
catch
{
// The code block which handle exception thrown by try block
}
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");}}}
exampleCatch
class.value
.exception
and is enclosed with the try
block.catch
block starts here. It catches the exception
.exception
thrown by the code.