Home java Java finally

Java finally

Author

Date

Category

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

That is, instead of

try {
  ...
} catch (Exception e) {
  ...
} finally {
  & lt; code & gt;
}

Write

try {
  ...
} catch (Exception e) {
  ...
}
& lt; code & gt;

Answer 1, authority 100%

The finally block will be executed even if you return in a try block, or if an exception is not caught in the block catch (for example, if there is no catch block, or the exception type is not the same as the type handled by the catch block). And also, if the code of the catch -block will throw an exception by itself. 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 manages to call System.exit () or the JVM crashes (or the process is externally destroyed in some way ).


Answer 2, authority 31%

The code in the finally block will always be executed, regardless of whether an exception is thrown or not. If you place the code just after the try-catch block, then if an exception is thrown, this code will not be executed, since the execution of the method will be interrupted due to the exception. Correct me if I’m wrong.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions