try, catch, finally- whats the point of finally?

A

Alan Paulk

It seems to me if you have a function like this

public void blah()

try
{
blah blah;
}

catch
{
blah de blah;
}

#code that executes whether there is an error or not#

return;

Then the code at the end will execute just as if it were in a finally
block. If that is the case then I don't know what the point of a
finally block is. Couls someone clear that up for me?

-Alan
 
J

Justin Rogers

finally is a guarantee that the code will get run. Take this example:

try {
 
J

Justin Rogers

Darnit, sorry, the Ctrl+Enter bug hit again.

Take this code:

try {
// Throw your exception
} finally {
// Run your clean-up here
}

The exception will bubble up the call stack and get caught by
another catch block if one exists, but your finally code will still
get run. If you placed the code outside of the finally block, then
execution would stop at the exception and be thrown up the stack
to be caught. Let's take a resource allocation example.

try {
// My library accesses a stream
// Some error happens and I need to throw an exception for the user.
throw new Exception("Invalid data was in the stream");
} finally {
// Close the stream here
}
 
G

Guest

Also, code in a catch block gets called *only* if an exception is thrown. Code in a finally block gets called if an exception is thrown or if an exception is *not* thrown.
 
A

Alan Paulk

Justin Rogers said:
Darnit, sorry, the Ctrl+Enter bug hit again.

Take this code:

try {
// Throw your exception
} finally {
// Run your clean-up here
}

The exception will bubble up the call stack and get caught by
another catch block if one exists, but your finally code will still
get run. If you placed the code outside of the finally block, then
execution would stop at the exception and be thrown up the stack
to be caught. Let's take a resource allocation example.

try {
// My library accesses a stream
// Some error happens and I need to throw an exception for the user.
throw new Exception("Invalid data was in the stream");
} finally {
// Close the stream here
}

Thanks for the help!
-Alan
 
S

Stu Smith

(lots of snip)
Most C++ programmers (including myself!) think the finally clause is
an absolute godsend!

As far as I'm aware the reason that Stroustrup didn't put finally into C++
is because there is a much better idiom in that language: destruction of
stack-based objects.

C# (and .NET), which don't support deterministic finalization, needed an
alternative method of safely releasing resources etc.

Stu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top