Sobes.tech
Junior — Middle

How do exceptions and errors occur in Java, and how to handle them correctly?

sobes.tech AI

Answer from AI

In Java, exceptions and errors occur during program execution when unforeseen situations arise, such as division by zero, null reference, input-output errors, etc.

Exceptions are of two types:

  • Checked exceptions — require mandatory handling or declaration in the method (e.g., IOException).
  • Unchecked exceptions — descendants of RuntimeException, handling is optional (e.g., NullPointerException).

Errors — serious problems that are usually not handled (e.g., OutOfMemoryError).

To handle exceptions, the try-catch-finally construct is used:

try {
    // code that may throw an exception
} catch (ExceptionType e) {
    // handle exception
} finally {
    // code that will execute in any case
}

Exceptions can also be propagated further using throws in the method declaration.

Proper exception handling includes:

  • Catch only those exceptions that can be handled
  • Do not suppress exceptions without reason
  • Use finally or try-with-resources to release resources

Example:

try {
    int result = 10 / divisor;
} catch (ArithmeticException e) {
    System.out.println("Division by zero is not possible");
}