Java Exceptions and Catch Clause
Java Exceptions and Catch Clause
337
28-Jul-2023
Updated on 29-Jul-2023
Aryan Kumar
29-Jul-2023A try-catch block is a block of code that can be used to handle exceptions. If an exception is thrown in a try-catch block, the exception will be caught by the catch block and the code in the catch block will be executed.
The syntax for a try-catch block is as follows:
The
tryblock contains the code that could potentially throw an exception. Thecatchblock is used to handle the exception. TheExceptionkeyword is a placeholder for the type of exception that can be caught.Here is an example of a try-catch block:
In this example, the
tryblock contains the code that could potentially throw an exception. The code that could throw an exception is theint z = x / y;statement. If theyvariable is equal to 0, then theArithmeticExceptionexception will be thrown.The
catchblock is used to handle theArithmeticExceptionexception. Thecatchblock will be executed if theArithmeticExceptionexception is thrown. Thecatchblock will then print the message "Division by zero".If the
yvariable is not equal to 0, then theArithmeticExceptionexception will not be thrown. In this case, thetryblock will execute normally and thecatchblock will not be executed.