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();
}
}
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With