473,698 Members | 2,371 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why finally?

Ken
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.

So... what is the difference between a "finally" block and
nothing at all?

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
}

Now, consider something similar:

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}

Console.Write(" i = {0}", i);
}

Nov 15 '05 #1
16 7940
Ken <kr****@fnis.co m> wrote:
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.

So... what is the difference between a "finally" block and
nothing at all?


The difference is when an exception *isn't* caught, but is propagated
up the stack, or when the catch block terminates the method (returns or
throws an exception itself). This doesn't happen in your case, because
you're catching Exception (well, I suppose it will happen if some non-
CLS compliant exception, or an uncatchable exception, is thrown).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #2
Ken,
Consider the following:
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
} catch (ApplicationExc eption e) {
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
Where I only want to catch ApplicationExce ptions, other kind of exceptions
will be handled outside of this routine.

For any kind of exception Application or otherwise I want the finally to be
executed.

Also finally is useful if you want to catch the exception, log it, then
rethrow the exception so others can deal with it.

catch (Exception ex)
{
ExceptionHandle r(ex); // logs the exception
throw; // (re) throws the caught exception
}
finally
{
// do clean up here
}

Hope this helps
Jay

"Ken" <kr****@fnis.co m> wrote in message
news:01******** *************** *****@phx.gbl.. . What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.

So... what is the difference between a "finally" block and
nothing at all?

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
}

Now, consider something similar:

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}

Console.Write(" i = {0}", i);
}

Nov 15 '05 #3
Ken,

Having a finally block ensures that the code inside of it will always be
executed before the function is exited.

example:

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
// if you do not have an exception return
return; // normally this would exit the function, however because
finally{} that code will be executed as well.
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
throw e; // this would cause function exit too- with finally{} that
code will be executed!
}
finally
{
Console.Write(" i = {0}", i);
}
}

finally{} is a great place to put resource clean up code- ensuring that it
always gets executed before returning!
Examples are things such as .Close() of streams, messaging, signalling, etc.
As most importantly, if you work with critical sections, mutex's etc. You
should put that release of those objects in a finally{} to ensure that they
are released so you don't encounter a deadlock, or resource indefinitely
locked issues.
Erin.

"Ken" <kr****@fnis.co m> wrote in message
news:01******** *************** *****@phx.gbl.. .
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.

So... what is the difference between a "finally" block and
nothing at all?

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
}

Now, consider something similar:

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}

Console.Write(" i = {0}", i);
}

Nov 15 '05 #4
Lots of reasons.. imagine you have a number of Catch()'s.. different
ones that catch different type of exceptions. One that catches an
IOException and one that catches a MalNumberformat or whatever. Suppose
the MalNumberFormat exception might occur at the very start of the
method and the IOException might occur near the end of the method. Also
suppose that you already have a file opened or a scarse resource in use
*before* the line where a NumberFormat exception can be thrown. Now if
your program at runtime encounters a NumberFormat exception, you might
end up with that scarce resource un-closed because it wasn't normally
closed after being used after the lines in the method that make use of
it (which are near the end of the method). Now also suppose that the
Catch(NumberFor matException) block deals with this problem a little
differently, in that, it 'retries' the method by jumping over to a label
in the method to the line where the exception was thrown, just to give
it another try... it would then not be wise to close the file in this
catch block. Similarly, after triend a couple of times, you might want
to jump off to another part of the code in the catch block and might not
ever release the file or the resource. 'finally' gives you the
assurances that the peice of code inside 'finally' will always be called
and so you can safely release your resources and close them 'properly'
in whatever manner you wish. Finally has a number of other similar uses.
Hope that clears a bit...
-Andre

Ken wrote:
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.

So... what is the difference between a "finally" block and
nothing at all?

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
}

Now, consider something similar:

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}

Console.Write(" i = {0}", i);
}


Nov 15 '05 #5

When an error is generated the runtime checks to see if
there is a finally block and if one is found then it is
executed. Any other code after finally will not be reached
as an error was generated and it is to be dealt with

The finally block is executed even if there is no error
This is helpful for code cleanup example to close file
references etc.. as it is always guaranteed to be executed
hope this helps

regards

tribal
-----Original Message-----
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentatio n. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should stillexecute since it comes after the whole thing.

So... what is the difference between a "finally" block andnothing at all?

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
}

Now, consider something similar:

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}

Console.Write(" i = {0}", i);
}

.

Nov 15 '05 #6
Ken
Thanks! This is the difference I was looking for. The
documentation did not make it clear to me that a finally
block was executed even if the "catch" block exited the
function. Now I can clearly see their benefit.
-----Original Message-----
Ken,
Consider the following:
try
{
// Invalid conversion; o contains a string not an int i = (int) o;
} catch (ApplicationExc eption e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}


Where I only want to catch ApplicationExce ptions, other

kind of exceptionswill be handled outside of this routine.

For any kind of exception Application or otherwise I want the finally to beexecuted.

Also finally is useful if you want to catch the exception, log it, thenrethrow the exception so others can deal with it.

catch (Exception ex)
{
ExceptionHandle r(ex); // logs the exception
throw; // (re) throws the caught exception
}
finally
{
// do clean up here
}

Hope this helps
Jay

"Ken" <kr****@fnis.co m> wrote in message
news:01******* *************** ******@phx.gbl. ..
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still execute since it comes after the whole thing.

So... what is the difference between a "finally" block and nothing at all?

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}
finally
{
Console.Write(" i = {0}", i);
}
}

Now, consider something similar:

void foo()
{
int i = 123;
string s = "Some string";
object o = s;

try
{
// Invalid conversion; o contains a string not an int i = (int) o;
}
catch (Exception e)
{
Console.WriteLi ne("Exception!" );
}

Console.Write(" i = {0}", i);
}

.

Nov 15 '05 #7
Jon, you cannot return from a try catch finally block. You will get an
error

JIM

"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
Ken <kr****@fnis.co m> wrote:
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.

So... what is the difference between a "finally" block and
nothing at all?


The difference is when an exception *isn't* caught, but is propagated
up the stack, or when the catch block terminates the method (returns or
throws an exception itself). This doesn't happen in your case, because
you're catching Exception (well, I suppose it will happen if some non-
CLS compliant exception, or an uncatchable exception, is thrown).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

Nov 15 '05 #8
james <no****@hyperco n.net> wrote:
Jon, you cannot return from a try catch finally block. You will get an
error


You can't return from a finally block, but you can most definitely
return from try and catch blocks:

using System;

public class Test
{

static void Main()
{
string x = ReturnFromTry() ;
Console.WriteLi ne (x);
x = ReturnFromCatch ();
Console.WriteLi ne (x);
}

static string ReturnFromTry()
{
try
{
return "try";
}
catch
{
}
finally
{
Console.WriteLi ne ("Finally");
}
return "Oops";
}

static string ReturnFromCatch ()
{
try
{
throw new Exception();
}
catch
{
return "catch";
}
finally
{
Console.WriteLi ne ("Finally");
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #9
Yep, I guess I misread, I was thinking of return from finally.
Which by the way is kind of a pain not being able to do that.
JIM

"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
james <no****@hyperco n.net> wrote:
Jon, you cannot return from a try catch finally block. You will get an
error


You can't return from a finally block, but you can most definitely
return from try and catch blocks:

using System;

public class Test
{

static void Main()
{
string x = ReturnFromTry() ;
Console.WriteLi ne (x);
x = ReturnFromCatch ();
Console.WriteLi ne (x);
}

static string ReturnFromTry()
{
try
{
return "try";
}
catch
{
}
finally
{
Console.WriteLi ne ("Finally");
}
return "Oops";
}

static string ReturnFromCatch ()
{
try
{
throw new Exception();
}
catch
{
return "catch";
}
finally
{
Console.WriteLi ne ("Finally");
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2947
by: Brian Alexander | last post by:
Hello; I'm curious to know how people preserve exceptions that arise in a try ... finally block. Consider this example: try: getResource() doSomething() finally: alwaysFreeResource()
26
2514
by: djw | last post by:
Hi, Folks- I have a question regarding the "proper" use of try: finally:... Consider some code like this: d = Device.open() try: d.someMethodThatCanRaiseError(...) if SomeCondition: raise Error # Error is subclass of Exception
16
10082
by: Bill | last post by:
Say I have a childThread currently is running a finally block to cleanup external resources. At the same time the main thread calls childThread.Abort(). The question is: when the ThreadAbortException is thrown, does the childThread finish the remaining code in the finally block?
3
4825
by: Brian | last post by:
Is it possible to have more than one try/catch/finally block within a method? Also, if the code never enters the try block of code, is the finally block executed? I have a try block in a branch of a switch statement and I only want the finally to execute if the branch of the switch statement is executed.
8
2733
by: Z D | last post by:
Hi, I was wondering what's the point of "finally" is in a try..catch..finally block? Isn't it the same to put the code that would be in the "finally" section right after the try/catch block? (ie, forget the finally block and just end the try/catch and put the code after the try/catch block). Or does the "finally" construct add some additional functionality?
16
2082
by: Chris | last post by:
Hi, regarding exception-handling : why put code in a 'finally' block, and not just after a 'catch'-block --> Example using 'finally ' : try { OpenFile();
7
1720
by: Sean Kirkpatrick | last post by:
I got caught with my pants down the other day when trying to explain Try...Catch...Finally and things didn't work as I had assumed. Perhaps someone can explain to me the purpose of Finally. I've looked at several texts that I have and none of them address this specific point. If I call some method that throws an exception in my routine Foo, sub foo call bar <- throws an exception do something else <- never get here
32
6118
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I understand Finally runs whether an error was caught or not, I haven't found a use for finally yet.
13
380
by: Jon Davis | last post by:
I understand that the finally sub-block will execute regardless of whether try succeeded or not. But so will code that follows try...catch. So then what is the difference between ... try { do.something.that.breaks(); } catch { do.something.that.works(); } cleanup();
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7739
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.