Java finally

Question:

Hello. What's the difference between using finally and putting the code just after the try-catch block?

That is, instead of

try {
    ...
}catch(Exception e){
    ...
}finally{
    <код>
}

Write a message

try {
    ...
}catch(Exception e){
    ...
}
<код>

The only thing that comes to mind is the presence in the try and catch blocks of the word return, and in the finally block of actions that are required at the end of the method.

Answer:

The finally block will be executed even if you return in the try block, or if the exception is not caught in the catch (for example, if there is no catch , or the type of the exception is not the same as the type handled by the catch ). And also if the catch block code itself throws an exception . In all these cases, the code after the finally block will not be executed.

By the way, the finally code will not be executed if the code before it has time to call System.exit() or the JVM crashes (or the process is externally destroyed in some way).

Scroll to Top