Questions tagged [finally]

The finally block always executes after a try block, regardless of how the control exits the block.

The finally block always executes after a try block, regardless of how the control exits the block. This includes whether:

  • The try block exits normally
  • The try block throws an exception caught by a local catch block
  • The try block throws an exception not caught by a local catch block.
  • The catch block exits normally.
  • The catch block itself throws an exception.
  • Any other statements leaving the block (e.g., goto, break, return).

It is useful for including commands which must be executed before exiting a code block. Often, it is used in connection with resource management.

5 questions
12
votes
5 answers

What is the conceptual difference between finally and a destructor?

First, I am well aware of Why is there no 'finally' construct in C++? but a lengthy-growing comment discussion on another question seems to warrant a separate question. Apart from the issue that finally in C# and Java can basically exist only once…
Martin Ba
  • 7,578
  • 7
  • 34
  • 56
8
votes
2 answers

How to get around non-initialized objects in the `finally` block?

I like using final variables whenever possible. Often those variables have to be closed afterwards. Note that I'm currently working on Java 6 so there is not closeable interface, but the same applies to later Java versions as well. For…
rath
  • 856
  • 8
  • 20
2
votes
1 answer

Event subscription in finally clause

Background My program communicates with a device that is usually asynchronous, but can sometimes behave synchronously. I have an event handler that I use for receiving the data asynchronously, then I have a separate event handler that I use when the…
Snoop
  • 2,718
  • 5
  • 24
  • 52
2
votes
1 answer

Which programming language first came up with the finally block?

Which programming language first came up with the finally block? I ask purely out of curiosity. It is a very useful piece of syntactic sugar, and whoever first created it surely has a very impressive grasp of solutions to programming…
patstuart
  • 643
  • 5
  • 12
-1
votes
5 answers

Finally block when no exceptions thrown

I'm doing some cleanup operations that could throw an exception, and I want to implement the logic of a finally block, but only if no exceptions are thrown: The initial implementation is this: acquireResource(); try { // stuff } catch (Exception…
thecoop
  • 491
  • 1
  • 5
  • 13