Reputation: 15303
If I have a method like the following can I omit the catch block here to achieve the same results?:
private ClassInstance GetMeANumber()
{
Resource a = null;
try
{
Resource a = new Resource();
return a.GetClassInstance();
}
catch
{
throw;
}
finally
{
if(a != null)
a.Dispose();
}
}
Upvotes: 5
Views: 698
Reputation: 81159
The "simply rethrow" catch block will have a few effects, which you may or may not like:
In general, I would regard the behaviors indicated above as undesirable, but in some cases one might want to ensure that inner "finally" blocks to run to conclusion even if the outer unhandled-exception trap might want to kill the application before the outer ones can run.
Upvotes: 2
Reputation: 5232
Just as a point of interest, the code pattern you've posted is pretty much what a using block would translate into. So your code can be rewritten as;
private ClassInstance GetMeANumber()
{
using (var a = new Resource())
{
return a.GetClassInstance();
}
}
Upvotes: 0
Reputation: 37192
Yes, that would be exactly the same.
However, a more common pattern is to implement IDisposable on Resource
. Then you can use using to acheive the same thing more concisely.
using (Resource a = new Resource()) {
return a.GetClassInstance();
}
Upvotes: 18