In Java, the try-catch block is a mechanism used for handling exceptions in code. The try block is used to enclose the code that might throw an exception, and the catch block is used to handle the exception if it occurs.
Here's an example of a try-catch block:
try {
// code that might throw an exception
} catch (ExceptionType1 e1) {
// code to handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// code to handle exception of type ExceptionType2
} finally {
// code that will be executed whether an exception occurs or not
}
In this example, the try block contains the code that might throw an exception. If an exception occurs, the catch block is executed to handle the exception. The catch block can handle different types of exceptions, depending on the type of exception that occurred. Multiple catch blocks can be used to handle different types of exceptions.
The finally block is optional and contains code that will be executed whether or not an exception occurs. This block is often used to release resources or perform other cleanup operations.
There are three types of try-catch blocks in Java:
1. Single try block with multiple catch blocks:This type of try-catch block is used when there are multiple exceptions that can occur in a program, and each exception needs to be handled differently. In this type of block, there is only one try block, but multiple catch blocks are used to catch different types of exceptions.
try {
// code that may throw exception
} catch (NullPointerException e) {
// code to handle NullPointerException
} catch (ArithmeticException e) {
// code to handle ArithmeticException
} catch (Exception e) {
// code to handle any other exception
}
2. Try block with finally block:
This type of try-catch block is used when there is some code that needs to be executed regardless of whether an exception occurs or not. The code in the finally block is always executed, even if an exception is thrown.
try {
// code that may throw exception
} catch (Exception e) {
// code to handle exception
} finally {
// code that is always executed
}
3. Nested try-catch blocks:
This type of try-catch block is used when there is a possibility of an exception within an exception. In this type of block, there is a try block within another try block, and the inner catch block handles the exception first. If the inner catch block is not able to handle the exception, then the outer catch block handles it.
try {
try {
// code that may throw exception
} catch (NullPointerException e) {
// code to handle NullPointerException
}
} catch (ArithmeticException e) {
// code to handle ArithmeticException
} catch (Exception e) {
// code to handle any other exception
}
Happy Coding :)