开发者

Try Finally or Try Catch Finally

开发者 https://www.devze.com 2023-02-28 01:52 出处:网络
If I have a method like the following can I omit the catch block h开发者_运维百科ere to achieve the same results?:

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:

  1. 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.
  2. All implicit or explicit nested "finally" blocks will run their course before the first-pass exception handling scans up the stack, i.e. before:
    1. Any outer filter blocks get a chance to run
    2. The debugger discovers that the exception will be ultimately unhandled
    3. An outer scope has a chance to discover that the exception will be ultimately unhandled and kill the application without running nested "finally" blocks.
  3. 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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消