About FINALLY clause

H

Henri

This question is applicable to all the languages, but could someone provide
me with an code example where FINALLY is really necessary.
FINALLY is often used for this kind of code:

Try
....
open a file
read some date
.....
Catch
... dealing with the file error ....
Finally
close the file
End Try

But wouldn't the following (without FINALLY) work as well?

Try
....
open a file
read some date
.....
Catch
... dealing with the file error ....
End Try
close the file

Please tell me what I'm missing.
Thanks
Henri
 
K

Karl Seguin

NO!

What happens if you can't "deal" with the file..say because the exception
was OutOfMemory (not what you thought it was going to be eh?) you should
still do what you can to close the file. Also, what happens in your
"dealing" with the exception that you decide to throw it...your close call
will never get called. The point of finally is that you are [almost]
guaranteed that the code will get called. Putting your cleanup AFTER the
try/catch doesn't provide a guarantee. Here's another case....your catch
code generates an exception...your cleanup will never get called.

Karl
 
S

Steve C. Orr [MVP, MCSD]

Try
....
open a file
read some date
.....
Catch
... dealing with the file error ....
.... exit sub or rethrow error ...
Finally
close the file
End Try

In the above code the exit sub or rethrow error would normally exit the
function, and if an error occurs within the Catch block the function would
also be exited. Anything after the try block would not be executed.
However, anything within the Finally block will be executed before the
function is exited. That is why it is useful.
 
D

DKode

I believe if you throw an exception from your catch clause, it will not
execute code outside of your try-catch clause if you throw an exception
up the stack. Any code you put inside of finally will run whether you
throw exceptions or not regardless.

anyone correct me if i am wrong.
 
H

Henri

Thanks to all for your answers !
FINALLY I could understand the use of FINALLY ;-)

Henri
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top