Use a 'try-finally' block without a 'catch' block
C#.NetExceptionException HandlingC# Problem Overview
Are there situations where it is appropriate to use a try-finally
block without a catch
block?
C# Solutions
Solution 1 - C#
You would use it to ensure some actions occur after the try
content or on an exception, but when you don't wish to consume that exception.
Just to be clear, this doesn't hide exceptions. The finally
block is run before the exception is propagated up the call stack.
You would also inadvertently use it when you use the using
keyword, because this compiles into a try-finally
(not an exact conversion, but for argument's sake it is close enough).
try
{
TrySomeCodeThatMightException();
}
finally
{
CleanupEvenOnFailure();
}
Code running in finally
is not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the finally
isn't your biggest problem :-) so basically don't sweat it.
Update from Tobias: finally
will not run if the process is killed.
Update from Paddy: https://stackoverflow.com/questions/111597/conditions-when-finally-does-not-execute-in-a-net-try-finally-block
The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:
using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-)
{
// Do stuff.
}
Compiles into something like:
SqlConnection conn;
try
{
conn = new SqlConnection("");
// Do stuff.
}
finally
{
if (conn != null)
conn.Dispose();
}
Solution 2 - C#
Good Explaination using code:
void MyMethod1()
{
try
{
MyMethod2();
MyMethod3();
}
catch(Exception e)
{
//do something with the exception
}
}
void MyMethod2()
{
try
{
//perform actions that need cleaning up
}
finally
{
//clean up
}
}
void MyMethod3()
{
//do something
}
If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.
Solution 3 - C#
using
is equivalent try-finally
. You will only use try-finally
when you want to do some clean up inside finally
and don't care about the exception.
The best approach will be
try
{
using(resource)
{
//Do something here
}
}catch(Exception)
{
//Handle Error
}
Doing so even clean up called by using
fails, your code will not fail.
There are some condition when finally
will not get executed.
- If there is any
StackOverflowException
orExecutingEngineException
. - Process is killed from external source.
Hope this answers your doubt.
Solution 4 - C#
If you have, for example an unmanaged resource you create and use in the try block, you can use the finally block to ensure you release that resource. The finally block will always be executed despite what happens (e.g. exceptions) in the try block.
E.g. the lock(x) statement is really:
System.Threading.Monitor.Enter(x);
try { ... }
finally
{
System.Threading.Monitor.Exit(x);
}
The finally block will always get called to ensure the exclusive lock is released.
Solution 5 - C#
You need a finally block, when no matter which (if any) exceptions are caught or even if none are caught you still want to execute some code before the block exits. For instance, you might want to close an open file.
See Also try-finally
Solution 6 - C#
try/finally: when you do not want to handle any exceptions but want to ensure some action(s) occur whether or not an exception is thrown by called code.
Solution 7 - C#
I don't know anything about C#, but it seems that anything you could do with a try-finally, you could more elegantly do with a using statement. C++ doesn't even have a finally as a result of its RAII.
Solution 8 - C#
Here is a situation where you might want to use try finally: when you would normally use a using statement, but can't because you are calling a method by reflection.
This won't work
using (objMsg = Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("omApp.MessagingBO")))
{
}
instead use
object objMsg = null;
try
{
objMsg
= Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("myAssembly.objBO"));
strResponse = (string)objMsg.GetType().InvokeMember("MyMethod", BindingFlags.Public
| BindingFlags.Instance | BindingFlags.InvokeMethod, null, objMsg,
new object[] { vxmlRequest.OuterXml });
}
finally
{
if (objMsg!=null)
((IDisposable)objMsg).Dispose();
}
Solution 9 - C#
Have a look at the following link: https://softwareengineering.stackexchange.com/questions/131397/why-use-try-finally-without-a-catch-clause
It depends on the architecture of your application and the operation you are performing in the block.
Solution 10 - C#
Here's a use case that I always (uhm..) use:
int? x; //note the nullable type here!
try
{
x = int.Parse(someString);
}
catch { } //don't care, let it just be null
Solution 11 - C#
1.we can use the try block without catch but we should use the catch/finally, any one of them. 2.We can't use only try block.