Java catch block
Created By: chatGPT
Java's catch block is used to handle exceptions that may occur during program execution. When an exception is thrown, the normal flow of execution is disrupted, and the catch block provides a way to handle the error gracefully without crashing the program. The catch block is always associated with a try block. Here’s how it works:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
You can specify multiple catch blocks to handle different types of exceptions. For instance, if you want to handle both ArithmeticException and NullPointerException separately, you can do it like this:
try {
// Code that may throw an exception
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred.");
} catch (NullPointerException e) {
System.out.println("Null pointer error occurred.");
}
It's also possible to use a multi-catch block to handle different exceptions in a single block, which can reduce code duplication. Here is an example:
try {
// Code that may throw an exception
} catch (ArithmeticException | NullPointerException e) {
System.out.println("An error occurred: " + e.getMessage());
}
In Java, the finally block can be added after the catch block to execute code regardless of whether an exception was thrown or caught. This is useful for releasing resources, such as closing a file or database connection.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
} finally {
// Cleanup code, executed regardless of exception
}