The Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at a particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in a try block that will not throw an exception.
The try block is used to enclose the code that might throw an exception during execution. Any code that has the potential to cause an error, such as division by zero, accessing an invalid array index, or reading a file, should be placed inside the try block.
The catch block is used to handle the exception thrown by the try block. You specify the type of exception to catch inside parentheses. When an exception occurs in the try block, the corresponding catch block executes.
The syntax of the try-catch block is as follows:
Here:
When an exception occurs, the Java Virtual Machine (JVM) first checks whether the exception is handled by the program.
This mechanism makes sure that exceptions do not always crash the program and gives programmers a way to recover from runtime errors gracefully.
The following image demonstrates how try-catch block works.

The following example demonstrates how a divide by zero scenario is handled using a try-catch block.
Output:
Error: Division by zero is not allowed. Program continues after exception handling.
You can also use the nested try-catch block that means a try-catch block placed inside another try or catch block. This is useful when you want to handle different types of exceptions separately at different levels of your code.
Here is the syntax of using nested try-catch block:
The following example demonstrates nested try catch block:
Output:
Outer try block starts Inner catch: Arithmetic Exception occurred Outer catch: Array Index Out Of Bounds Exception occurred Program continues after nested exception handling.
Explanation:
Let's try to understand the problem if we do not use a try-catch block to handle the exception.
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As we see in the above example, the rest of the code is not executed (in such a case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the code below the exception will not execute.
Let's see the solution to the above problem by using a Java try-catch block.
Output:
java.lang.ArithmeticException: / by zero rest of the code
As we see in the above program, the rest of the code is executed, i.e., the rest of the code statement is printed on the console.
We request you to subscribe our newsletter for upcoming updates.