Junior — Middle
What methods can be used to intercept and handle errors in a program?
sobes.tech AI
Answer from AI
In Java, exception handling constructs are used for catching and managing errors:
- try-catch — a block that contains code that might throw an exception and a handler for it.
- finally — a block that always executes, regardless of whether an exception was thrown or not, usually for resource cleanup.
- throw — an operator for explicitly throwing an exception.
- throws — a method declaration indicating it may throw certain exceptions.
Example:
try {
int result = 10 / divisor; // may throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Division by zero!");
} finally {
System.out.println("Finally block executed");
}
You can also create your own exception classes by inheriting from Exception or RuntimeException to manage errors more precisely.