Junior — Middle
How to implement exception handling in Java code?
sobes.tech AI
Answer from AI
In Java, exception handling is implemented using try-catch-finally blocks. Code that may throw an exception is placed inside the try block. Exceptions are caught in catch blocks, where errors can be handled. The finally block is always executed, regardless of whether an exception occurred or not.
Example:
try {
int result = 10 / divisor; // may throw ArithmeticException if divisor is 0
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: division by zero!");
} finally {
System.out.println("Finally block executed.");
}
You can also create custom exceptions by inheriting from Exception or RuntimeException. Exception handling helps make the program more robust and controllable in case of errors.