Appearance
Exception Handling
try-catch Blocks:
Exception handling allows you to handle errors gracefully using try-catch
blocks.
java
// try-catch block
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
Multiple Catch Blocks:
You can handle multiple exceptions in a single try-catch
block.
java
// Multiple catch blocks
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds.");
} catch (Exception e) {
System.out.println("An error occurred.");
}
Custom Exceptions:
You can create custom exception classes by extending the Exception
class.
java
// Custom exceptions
public class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
try {
throw new MyCustomException("This is a custom exception.");
} catch (MyCustomException e) {
System.out.println(e.getMessage());
}