What is the point of the finally block?

In Java:

Finally always gets called, regardless of if the exception was correctly caught in catch(), or in fact if you have a catch at all.


Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.

In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.

In the .NET platform, in some cases the execution of the finally block won't occur: Security Exceptions, Thread suspensions, Computer shut down :), etc.


Well, for one thing, if you RETURN inside your try block, the finally will still run, but code listed below the try-catch-finally block will not.


try catch finally is pretty important construct. You can be sure that even if an exception is thrown, the code in finally block will be executed. It's very important in handling external resources to release them. Garbage collection won't do that for you. In finally part you shouldn't have return statements or throw exceptions. It's possible to do that, but it's a bad practice and can lead to unpredictable results.

If you try this example:

try {
  return 0;
} finally {
  return 2;
}

The result will be 2:)

Comparison to other languages: Return From Finally