Junior — Middle
Is it mandatory to include a finally block when using a catch block in exception handling?
sobes.tech AI
Answer from AI
No, the finally block is not mandatory when using a catch block in Java. The finally block is used to execute code that should run regardless of whether an exception was thrown or not.
Example:
try {
// code that might throw an exception
} catch (Exception e) {
// exception handling
} finally {
// code that always executes
}
If you do not need to perform any actions regardless of exceptions, the finally block can be omitted:
try {
// code
} catch (Exception e) {
// handling
}
Thus, finally is an optional block, not a mandatory one.