Why catch and rethrow an exception in C#?

前端 未结 17 1016
遥遥无期
遥遥无期 2020-11-22 14:56

I\'m looking at the article C# - Data Transfer Object on serializable DTOs.

The article includes this piece of code:

public static string Se         


        
17条回答
  •  佛祖请我去吃肉
    2020-11-22 15:06

    First; the way that the code in the article does it is evil. throw ex will reset the call stack in the exception to the point where this throw statement is; losing the information about where the exception actually was created.

    Second, if you just catch and re-throw like that, I see no added value, the code example above would be just as good (or, given the throw ex bit, even better) without the try-catch.

    However, there are cases where you might want to catch and rethrow an exception. Logging could be one of them:

    try 
    {
        // code that may throw exceptions    
    }
    catch(Exception ex) 
    {
        // add error logging here
        throw;
    }
    

提交回复
热议问题