473,804 Members | 3,461 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

try/catch/finally


I have always wondered what finally is actually for. What would be the
exact difference between

try
{
somecode1();
}
catch(Exception )
{
somecode2();
}
finally
{
somecode3();
}

somecode4();
..... and ....
try
{
somecode1();
}
catch(Exception )
{
somecode2();
}

somecode3();
somecode4();
Thanks,
Alexander
Nov 16 '05 #1
17 2358
Alexander,

Even when you set a return somewhere, the finally will be executed.

Cor
Nov 16 '05 #2
> I have always wondered what finally is actually for. What would be the
exact difference between

The finally gets ALWAYS executed, even when an exception is thrown.
And it doesn't block the thrown exception, it just executes the finally part
and continues with the exception.

A very good example for this would be to close a file in there.
This way the file is always closed even if an exception occurs.

--
http://www.skyscan.be
Nov 16 '05 #3
The difference is that the finally-block will be executed no matter what
happens (uncaught exceptions, exceptions thrown in catch-block and so
on). If your application fails, the first example will execute
somecode3() but not somecode4() as it will never get to that point. The
second example won't execute any of them (if the app fails, of course).
Finally is ideal for things like releasing database-connections, closing
files, sockets and other clean-up operations.

I have always wondered what finally is actually for. What would be the
exact difference between

try
{
somecode1();
}
catch(Exception )
{
somecode2();
}
finally
{
somecode3();
}

somecode4();
.... and ....
try
{
somecode1();
}
catch(Exception )
{
somecode2();
}

somecode3();
somecode4();
Thanks,
Alexander

Nov 16 '05 #4
Also, you are much more likely to want to perform some kind of cleanup rather than actually deal with an exception (theres no point in downstream code unless it can do something about the error). So you will much more commonly see the following than try ... catch.

// allocate some resource
try
{
// use the resource
}
finally
{
// clean up the resource
}

The clean up will occur whether ot not an exception occurs in the try block

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Alexander,

Even when you set a return somewhere, the finally will be executed.

Cor

Nov 16 '05 #5
Cor Ligthert wrote:
Alexander,

Even when you set a return somewhere, the finally will be executed.

Cor


Thanks Cor, but where "somewhere" exactly?

Alexander
Nov 16 '05 #6
Olaf Baeyens wrote:

The finally gets ALWAYS executed, even when an exception is thrown.
And it doesn't block the thrown exception, it just executes the finally part
and continues with the exception.

A very good example for this would be to close a file in there.
This way the file is always closed even if an exception occurs.


Thanks Olaf, so its the conclusion in my reply to Richard's posting?

Alexander
Nov 16 '05 #7
Richard Blewett [DevelopMentor] wrote:
Also, you are much more likely to want to perform some kind of cleanup rather than actually deal with an exception (theres no point in downstream code unless it can do something about the error). So you will much more commonly see the following than try ... catch.

// allocate some resource
try
{
// use the resource
}
finally
{
// clean up the resource
}

The clean up will occur whether ot not an exception occurs in the try block


So the actual difference is, that try/catch/finally doesnt make much
sense and by having try/finally the exception will be actually thrown as
normally to the caller (as if unhandled) but prior the code in finally
will be executed, right?

Alexander
Nov 16 '05 #8
Remigiusz Dybka wrote:
The difference is that the finally-block will be executed no matter what
happens (uncaught exceptions, exceptions thrown in catch-block and so
on). If your application fails, the first example will execute
somecode3() but not somecode4() as it will never get to that point. The
second example won't execute any of them (if the app fails, of course).
Finally is ideal for things like releasing database-connections, closing
files, sockets and other clean-up operations.


Thanks Remigiusz, but I dont see a reason why those should not be
executed. After all the exception is caught by the catch statement.

Alexander
Nov 16 '05 #9
Alexander Mueller wrote:
Cor Ligthert wrote:
Alexander,

Even when you set a return somewhere, the finally will be executed.

Cor


Thanks Cor, but where "somewhere" exactly?

Alexander


in the "try" or "catch" block

--
Hans Kesting
Nov 16 '05 #10

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

Similar topics

8
2738
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?
6
7133
by: Tilfried Weissenberger | last post by:
Hi, I am a bit confused as to what the FINALLY block is meant for. What's the difference between: this.Cursor = Cursors.WaitCursor; try { //do some stuff } catch { //handle exception } finally { this.Cursor = Cursors.Default; }
11
3494
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
23
3084
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally block. But, I prefer to dim them "on the fly" only if needed (save as much resources as possible). A little further... I may wish to create a sqlcommand and datareader object ONLY if certain conditions are met. But, if I want to clean these up in the...
2
1941
by: Ralph Krausse | last post by:
I created a try/catch/finally but when an expection is thrown, the catch does not handle it... (I know this code is wrong, I want to force the error for this example) try { DataSet ds = new DataSet(); string strID = ds.Tables.Rows.ToString(); }
13
1587
by: Woody Splawn | last post by:
I have a try catch statement in a fucntion that is supposed to return a true or a false My code looks like this: Try mySqlConnection.Open() Dim Da1 As New SqlDataAdapter("Select JnlType, Description from JnlType", mySqlConnection) Dim Ds As New DataSet("X")
7
1732
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
6132
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.
6
7451
by: foolmelon | last post by:
If a childThread is in the middle of a catch block and handling an exception caught, the main thread calls childThread.Abort(). At that time a ThreadAbortException is thrown in the childThread. The question is: after the ThreadAbortException is thrown, does the childThread continue run the remaining code in the catch block?
12
2698
by: David Lozzi | last post by:
Howdy, I ran into a very interesting issue and I'm curios as to how this is suppose to work. I am using Try...Catch...Finally statements for all database connectivity in my ASP.NET 2.0 web application. I'm connecting to IBM's Universe 10.2 using UniObjects.Net. Anyway, if the connection errors, the Finally closes the connection. What I see happening is that the function in the Finally statement either isn't running or doesn't apply what...
0
9576
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10567
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...
1
10310
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,...
0
10074
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
9138
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...
1
7613
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6847
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
5515
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...
0
5647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.