Difference between catch(Exception), catch() and just catch

前端 未结 5 737
借酒劲吻你
借酒劲吻你 2021-01-17 10:53

I want to know if I can safely write catch() only to catch all System.Exception types. Or do I\'ve to stick to catch(Exception) to accomplish this. I know for other exceptio

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 11:13

    If the fact that an exception occurs implies that you need to run a piece of code, but you wouldn't do anything with the exception except rethrow it if you caught it, the preferred approach is probably not to catch the exception but instead do something like:

      bool ok=false;
      try
      {
        ... do stuff -- see note below about 'return'
        ok = true;
      }
      finally
      {
        if (!ok)
        {
          ... cleanup code here
        }
      }
    

    The one weakness with this pattern is that one must manually add an ok = true; before any return statement that occurs within the try block (and ensure that there's no way an exception (other than perhaps ThreadAbortException) can occur between the ok = true; and the return). Otherwise, if one isn't going to do anything with an exception, one shouldn't catch it.

提交回复
热议问题