Why Re-throw Exceptions?

后端 未结 13 1757
借酒劲吻你
借酒劲吻你 2020-12-13 00:25

I\'ve seen the following code many times:

try
{
    ... // some code
}
catch (Exception ex)
{
    ... // Do something
    throw new CustomException(ex);

            


        
13条回答
  •  -上瘾入骨i
    2020-12-13 01:12

    Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it.

    Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead.

提交回复
热议问题