Why Re-throw Exceptions?

后端 未结 13 1758
借酒劲吻你
借酒劲吻你 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条回答
  •  攒了一身酷
    2020-12-13 00:50

    I think it depends on what you are trying to do with the exception.

    One good reason would be to log the error first in the catch, and then throw it up to the UI to generate a friendly error message with the option to see a more "advanced/detailed" view of the error, which contains the original error.

    Another approach is a "retry" approach, e.g., an error count is kept, and after a certain amount of retries that's the only time the error is sent up the stack (this is sometimes done for database access for database calls that timeout, or in accessing web services over slow networks).

    There will be a bunch of other reasons to do it though.

提交回复
热议问题