Junior — Middle
What are the ways to implement exception handling in a program?
sobes.tech AI
Answer from AI
In Java, exception handling is implemented using the try-catch-finally construct and the keywords throw and throws.
Main methods:
- try-catch: a block of code where an exception may occur is placed in
try. Exceptions are caught incatchblocks. - finally: a block that always executes after try/catch, for example, to release resources.
- throw: an operator for explicitly throwing an exception.
- throws: a declaration in the method signature that the method may throw exceptions that must be handled by the calling code.
Example:
try {
int result = 10 / 0; // will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Division by zero!");
} finally {
System.out.println("This block will execute in any case.");
}