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
16 7949
james <no****@hyperco n.net> wrote: 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.
Indeed. It would often be a mistake to do it, but it's occasionally
handy. (You can do it in Java, which is how I know it's handy sometimes
:)
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
So why would anyone want to return from within a finally block? Since
finally blocks are always executed, why not simply return after the full
try..catch...fi nally statement?
I suppose if you have so much logic in your finally block that you need to
return in some cases and not in others, it sounds like there's a problem
with the flow and design of the code.
Cheers,
Wim Hollebrandse http://www.wimdows.com http://www.wimdows.net
"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** @news.microsoft .com... james <no****@hyperco n.net> wrote: 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.
Indeed. It would often be a mistake to do it, but it's occasionally handy. (You can do it in Java, which is how I know it's handy sometimes :)
-- Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/ If replying to the group, please do not mail me too
"Wim Hollebrandse" <wimATwimdows.c om> <"Wim Hollebrandse"
<wimATwimdows.c om>> wrote: So why would anyone want to return from within a finally block? Since finally blocks are always executed, why not simply return after the full try..catch...fi nally statement?
Because you may have some conditional behaviour in the finally block -
and also potentially because you wish to return in order to override
any exception which may have occurred. For instance, you could have
something like:
object GetValue (object defaultValue)
{
object ret = defaultValue;
try
{
ret = AttemptToGetRea lValue();
}
finally
{
return ret;
}
}
Not something I'd often consider, admittedly (it masks too many
exceptions) - just an off-the-top-of-my-head example.
I suppose if you have so much logic in your finally block that you need to return in some cases and not in others, it sounds like there's a problem with the flow and design of the code.
There doesn't necessarily need to be *very* much logic in there. I'm
not saying I do it particularly often, but just occasionally it's
handy.
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
James,
Maybe its just me. :-) I would simply put the return in the try block.
Something like: int value = y; try { val = doSomthing(); if ( val == X ) return true; else return false; } catch ( exception e) { //handle it } finally { }
I would suspect the finally block was doing too much, if it needed to decide
what the return value was.
Hope this helps
Jay
"james" <no****@hyperco n.net> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. .. A more likely example is where the method return a boolean like so
int value = y; try { val = doSomthing(); } catch ( exception e) { //handle it } finally { if ( val == X ) return true; else return false; }
how can you be sure the proper return result is returned if you do not catch the exception ??
JIM
"Jon Skeet" <sk***@pobox.co m> wrote in message news:MP******** *************** *@news.microsof t.com... "Wim Hollebrandse" <wimATwimdows.c om> <"Wim Hollebrandse" <wimATwimdows.c om>> wrote: So why would anyone want to return from within a finally block? Since finally blocks are always executed, why not simply return after the
full try..catch...fi nally statement? Because you may have some conditional behaviour in the finally block - and also potentially because you wish to return in order to override any exception which may have occurred. For instance, you could have something like:
object GetValue (object defaultValue) { object ret = defaultValue;
try { ret = AttemptToGetRea lValue(); } finally { return ret; } }
Not something I'd often consider, admittedly (it masks too many exceptions) - just an off-the-top-of-my-head example.
I suppose if you have so much logic in your finally block that you
need to return in some cases and not in others, it sounds like there's a
problem with the flow and design of the code.
There doesn't necessarily need to be *very* much logic in there. I'm not saying I do it particularly often, but just occasionally it's handy.
-- Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/ If replying to the group, please do not mail me too
Jay B. Harlow [MVP - Outlook] <Ja********@ema il.msn.com> wrote: Maybe its just me. :-) I would simply put the return in the try block.
But then you've got to have another return statement either in the
finally block or after it, in case doSomething() throws an exception
which is caught.
I would suspect the finally block was doing too much, if it needed to decide what the return value was.
Usually, yes - but *sometimes* it's handy.
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jay B. Harlow [MVP - Outlook] <Ja********@ema il.msn.com> wrote: Lets says there is no exception, the program proceeds to the finally block, sees the return statement that returns a value. That mostly makes sense. Now lets say an exception was thrown, but is not caught!, the program proceeds to the finally block, sees the return statement with a value. Huh! I'm in the middle of raising an exception, do I evaluate the return and return the value, or do I continue raising the exception. Seeing as the exception has precedence I ignore the value on the return (it is evaluated, just not used) and continue to raise the exception.
Not in Java, at least - and if C# had return in finally, I'd expect it
not to be true in C# either. The last reason for terminating the method
(return or exception) is the one that takes priority. I realise this is
all hypothetical, but where did you get the "seeing as the exception
has precedence" idea from?
Unfortunately it's relatively hard to find any occasions in my existing
code where I've used return from a finally block - if I run into any in
the next few days, I'll post them. I don't expect to though - as I say,
I've only used it occasionally.
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jon, all hypothetical, but where did you get the "seeing as the exception has precedence" idea from?
I was trying to say that:
If you entered the finally block because of an exception, the block is
operating in the context of an exception handler, a value on the return is
immaterial.
If you entered the finally block as normal program flow (no exception), the
block is operating in the context of not being an exception handler, a value
on the return is material.
As you put it, the last reason for terminating the method (implicit or
explicit) return or an exception.
Jay
"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com... Jay B. Harlow [MVP - Outlook] <Ja********@ema il.msn.com> wrote: Lets says there is no exception, the program proceeds to the finally
block, sees the return statement that returns a value. That mostly makes sense. Now lets say an exception was thrown, but is not caught!, the program proceeds to the finally block, sees the return statement with a value.
Huh! I'm in the middle of raising an exception, do I evaluate the return and return the value, or do I continue raising the exception. Seeing as the exception has precedence I ignore the value on the return (it is
evaluated, just not used) and continue to raise the exception.
Not in Java, at least - and if C# had return in finally, I'd expect it not to be true in C# either. The last reason for terminating the method (return or exception) is the one that takes priority. I realise this is all hypothetical, but where did you get the "seeing as the exception has precedence" idea from?
Unfortunately it's relatively hard to find any occasions in my existing code where I've used return from a finally block - if I run into any in the next few days, I'll post them. I don't expect to though - as I say, I've only used it occasionally.
-- Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet/ If replying to the group, please do not mail me too This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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()
|
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
|
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?
|
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.
|
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?
| |
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();
|
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
|
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.
|
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();
|
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...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |