Sobes.tech
Junior — Middle

Can you explain what an exception is in Java and how it is used?

sobes.tech AI

Answer from AI

In Java, an exception is an object that signals the occurrence of an error or unusual situation during program execution. Exceptions are used for error handling and allow the program not to terminate abruptly.

There are two types of exceptions:

  • Checked (checked) — must be handled or declared in the method using throws.
  • Unchecked (unchecked) — inherit from RuntimeException, their handling is optional.

Example of usage:

try {
    int result = 10 / 0; // will cause ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Division by zero is not possible");
} finally {
    System.out.println("The finally block always executes");
}

Here, the try block contains code that may throw an exception, catch handles it, and finally executes in any case.

Can you explain what an exception is in Java and how… - sobes.tech