
233 views
Java Try-catch block
The try–catch block in Java is a fundamental construct used for exception handling. It allows you to write code that can potentially throw exceptions and then provide specific error-handling code to deal with those exceptions gracefully. Here’s how the try–catch block works:
tryBlock:
- The
tryblock encloses the code that might throw an exception. - The code within the
tryblock is monitored for exceptions. - If an exception occurs within the
tryblock, the normal flow of execution is immediately interrupted, and control is transferred to the appropriatecatchblock.
catchBlock:
- The
catchblock follows thetryblock and specifies the type of exception it can catch. - If the exception thrown within the
tryblock matches the type specified in thecatchblock, the code within thecatchblock is executed. - The
catchblock can access the caught exception using the exception parameter, allowing you to perform error-specific actions or logging.
- Example:
try {
// Code that may throw an exception
} catch (SomeException ex) {
// Code to handle SomeException
}
finallyBlock:
- Optionally, you can use a
finallyblock after thecatchblock. - The code within the
finallyblock is executed regardless of whether an exception was thrown or not. - It’s often used for cleanup operations that need to occur regardless of the exception situation.
- Example with
finally:
try {
// Code that may throw an exception
} catch (SomeException ex) {
// Code to handle SomeException
} finally {
// Cleanup or finalization code
}
Here’s a complete example illustrating the use of try–catch blocks:
public class ExceptionExample {
public static void main(String[] args) {
try {
int numerator = 10;
int denominator = 0;
int result = numerator / denominator; // This will throw an ArithmeticException
System.out.println("Result: " + result); // This line won't be reached
} catch (ArithmeticException ex) {
System.out.println("Error: " + ex.getMessage());
} finally {
System.out.println("Cleanup code here"); // This will be executed regardless of exception
}
System.out.println("Program continues"); // This line will be reached
}
}
In this example, a division by zero operation will throw an ArithmeticException. The catch block catches this exception and prints an error message. The finally block is used for cleanup. Even though an exception occurred, the program continues to execute after the try–catch block.