If I have a method like the following can I omit the catch block h开发者_运维百科ere 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:
- If the stack trace includes line numbers, the line number associated with the routine that catches and rethrows will be the line number of the rethrow, rather than the line number of the method call in which the exception occurred. In some cases, that can be very annoying.
- All implicit or explicit nested "finally" blocks will run their course before the first-pass exception handling scans up the stack, i.e. before:
- Any outer filter blocks get a chance to run
- The debugger discovers that the exception will be ultimately unhandled
- An outer scope has a chance to discover that the exception will be ultimately unhandled and kill the application without running nested "finally" blocks.
- If the debugger is set to trap on unhandled exceptions, it will trap at the location of the rethrow, rather than at the location where the exception occurred.
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.
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();
}
}
精彩评论