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

前端 未结 5 679
借酒劲吻你
借酒劲吻你 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:02

    In a perfect world, you shouldn't use catch(Exception) nor catch (alone) at all, because you should never catch the generic Exception exception. You always should catch more specific exceptions (for instance InvalidOperationException...etc.).

    In a real world, both catch(Exception) and catch (alone) are equivalent. I recommend using catch(Exception ex) when you plan to reuse the exception variable only, and catch (alone) in other cases. Just a matter of style for the second use case, but if personally find it more simple.

    What's really important (even if it's out of the scope of your question) is that you never write the following piece of code:

    try
    {
    }
    catch (SpecificException ex)
    {
        throw ex;
    }
    

    This would reset the stack trace to the point of the throw. In the other hand:

    try
    {
    }
    catch (SpecificException)
    {
        throw;
    }
    

    maintain the original stack trace.

提交回复
热议问题