Java Exception Handling
In Java, exception handling is a mechanism for handling errors or exceptional situations that ocurr during program execution. Java provides try-catch blocks to catch and handle exceptions, and finally blocks to perform cleanup operations. Below is a simple introduction and example code for Java exception handling.
Basic Structure of Exception Handling
- try block: Contains code that may throw a exception.
- catch block: Catches and hendles the exception thrown in the try block.
- finally block: Code block that executes regardless of whether an exception occurs.
Example Code
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Catch and handle ArithmeticException
System.out.println("Caught ArithmeticException: " + e.getMessage());
} finally {
// Code that always executes
System.out.println("Finally block executed");
}
}
public static int divide(int a, int b) {
return a / b; // This may throw ArithmeticException
}
}
Code Explanation
-
try block:
try { int result = divide(10, 0); System.out.println("Result: " + result); }This calls the
dividemethod and attempts to print the result. Since the divisor is 0, anArithmeticExceptionis thrown. -
catch block:
catch (ArithmeticException e) { System.out.println("Caught ArithmeticException: " + e.getMessage()); }Catches the
ArithmeticExceptionand prints the error message. -
finally block:
finally { System.out.println("Finally block executed"); }Regardless of whether an exception occurs, the code in the
finallyblock executes.
Output
Caught ArithmeticException: / by zero
Finally block executed
In this way, Java programs can gracefully handle runtime exceptions, avoid crashes, and provide useful error information.