Junior
What is an exception in Java?.
sobes.tech AI
Answer from AI
An exception in Java is an event that interrupts the normal flow of program execution during runtime. It indicates the occurrence of an error or an unforeseen situation.
Exceptions are handled using the try-catch-finally mechanism.
Exception hierarchy:
ThrowableError(serious errors from which recovery is usually impossible)Exception(less severe errors that can be handled)RuntimeException(unchecked exceptions that occur during execution, e.g.,NullPointerException)- Checked exceptions (require explicit handling or declaration in the method signature, e.g.,
IOException)
Purpose of exceptions:
- To separate code that generates an error from code that handles it.
- To improve the readability and reliability of the program.
- To prevent abrupt termination of the program.
Example of exception handling:
try {
// Code that may throw an exception
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
// Handling the exception
System.err.println("Division by zero error: " + e.getMessage());
} finally {
// Block that always executes, regardless of exception
System.out.println("Finally block executed.");
}