Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Finally or Try Catch Finally

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();
      }
}
like image 456
Cole W Avatar asked Apr 21 '11 12:04

Cole W


2 Answers

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();
}
like image 101
RB. Avatar answered Nov 17 '22 11:11

RB.


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.

like image 29
supercat Avatar answered Nov 17 '22 11:11

supercat