Junior — Middle
Kas on võimalik kasutada try-catch konstruktsiooni ilma catch plokita määramata ja millal see on vastuvõetav?
sobes.tech AI
Vastus AI-lt
In Java, the try construct without a catch block is possible, but only if there is a finally block. That is, you can write:
try {
// code that may throw an exception
} finally {
// code that will execute in any case
}
This approach is used when you need to guarantee the execution of some code (for example, releasing resources), but do not handle exceptions at this point — they will be propagated further.
However, you cannot write a try without catch and without finally — the compiler will produce an error.