Why Re-throw Exceptions?

后端 未结 13 1765
借酒劲吻你
借酒劲吻你 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 01:07

    I can think of the following reasons:

    • Keeping the set of thrown exception types fixed, as part of the API, so that the callers only have to worry about the fixed set of exceptions. In Java, you are practically forced to do that, because of the checked exceptions mechanism.

    • Adding some context information to the exception. For example, instead of letting the bare "record not found" pass through from the DB, you might want to catch it and add "... while processing order no XXX, looking for product YYY".

    • Doing some cleanup - closing files, rolling back transactions, freeing some handles.

提交回复
热议问题