Sobes.tech
Junior — Middle

Kas on võimalik kinni püüda erandeid, mis pole koodis otseselt deklareeritud?

sobes.tech AI

Vastus AI-lt

Yes, in Java you can catch exceptions that are not explicitly declared in the code. There are two types of exceptions in Java:

  • Checked exceptions — these must be declared in the method signature with throws or handled within a try-catch block.
  • Unchecked exceptions — these are subclasses of RuntimeException and Error. They do not need to be declared and can be caught, although they are usually not handled specifically.

For example, you can catch any exception with catch (Exception e), even if it is not declared in the method:

try {
    // code that may throw an exception
} catch (Exception e) {
    // handle any exception
}

This way, you can catch any exception, but for checked exceptions, the compiler requires them to be declared or handled.