try/catch/finally

  • Thread starter Thread starter Alexander Mueller
  • Start date Start date
A

Alexander Mueller

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
 
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.
 
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
 
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.
 
Richard said:
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
 
Olaf said:
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
 
Remigiusz said:
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
 
well try...catch...finally does make sense in some situations - where you want to deal with the exception *and* you want to ensure cleanup (what happens if something throws in your catch block). But yes try...finally means the exception gets propagated and the finally block executes

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
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
 
Alexander,

Than your sample

try
{
Return();
}
catch(Exception)
{
Return();
}
finally
{
Console.WriteLine("Hello");
}

Console.WriteLine("Hello");

..... and ....
try
{
return();
}
catch(Exception)
{
return();
}

Console.WriteLine("Hello");
Console.WriteLine("Whatever");

Until you powerdown, will sample 1 always show "Hello" and that is all, the
sample2 will show nothing.

I hope that this makes it clear?

Cor
 
Richard said:
well try...catch...finally does make sense in some situations - where you want to deal with the exception *and* you want to ensure cleanup (what happens if something throws in your catch block).

Well, so in "normal" situations (not having a catch block with possible
exceptions) the two mentioned examples are more or less identical.
But yes try...finally means the exception gets propagated and the finally block executes

Alright, thank you.
 
Alexander,
Thanks Cor, but where "somewhere" exactly?


Than your sample

try
{
Return();
}
catch(Exception)
{
Return();
}
finally
{
Console.WriteLine("Hello");
}

Console.WriteLine("Hello");

..... and ....
try
{
return();
}
catch(Exception)
{
return();
}

Console.WriteLine("Hello");
Console.WriteLine("Whatever");

I think that this are a lot of somewhere's

Until you powerdown, will sample1 always show "Hello" and that is all,
sample2 will show nothing.

I hope that this makes it clear?

Cor
 
Alexander said:
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

but what if you catch specific exceptions?

try
{
DoSomething();
}
catch (NullReferenceException)
{
}
CleanUp();

will not execute the Cleanup() if an exception other than
NullReferenceException (or derived from that) has occurred.
And what if the code in your cleanup itself crashes? The finally
is still executed then.

And "finally", it also shows that you *really* want it cleaned up,
if you use "finally".
 
Dim conn As SqlConnection = New SqlConnection(...);

conn.Open();

try {
// Update/Insert/Select code here.
} catch (SqlException Ex) {
// Log or display or otherwise handle the SqlException.
Console.WriteLine("A non-critical exception occurred: " + Ex.Message);
} catch (Exception Ex) {
// Log or display the Exception.
Console.WriteLine("A critical exception occurred: " + Ex.ToString());
return;
} finally {
// Cleanup.
// We always want the connection to be closed. Therefore, we place the
// connection Close method in the finally. Remember, the Open method
// should be called before the try...catch block, maybe in another
// try...catch block of it's own.
conn.Close();
}

// Do stuff whith data retrieve, or show messages that the operation was
successful.


Hope this helps clarify one reason and way to use try...catch...finally :)

Mythran
 
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?

The catch could be interesting if you want to catch a specific exception but
let all other through.

Another important aspect of the try-catch thing, is to only catch real
exceptional cases.
I mean don't use it as a way to return an error code that happens often.

For example: throwing an exception because of a file that does not exist is
not good to do, if it is used just for testing if a file exist. Better to
return a boolean in this case. But if the file is critical and should be
there beause it is critcal for the application, then raising an exception
could be used, but only if it is a rare condition.
 
Back
Top