Why Re-throw Exceptions?

后端 未结 13 1728
借酒劲吻你
借酒劲吻你 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:14

    If you look at exceptions as on an alternative way to get a method result, then re-throwing an exception is like wrapping your result into some other object.

    And this is a common operation in a non-exceptional world. Usually this happens on a border of two application layers - when a function from layer B calls a function from layer C, it transforms C's result into B's internal form.

    A -- calls --> B -- calls --> C

    If it doesn't, then at the layer A which calls the layer B there will be a full set of JDK exceptions to handle. :-)

    As also the accepted answer points out, layer A might not even be aware of C's exception.

    Example

    Layer A, servlet: retrieves an image and it's meta information
    Layer B, JPEG library: collects available DCIM tags to parse a JPEG file
    Layer C, a simple DB: a class reading string records from a random access file. Some bytes are broken, so it throws an exception saying "can't read UTF-8 string for record 'bibliographicCitation'".

    So A won't understand the meaning of 'bibliographicCitation'. So B should translate this exception for A into TagsReadingException which wraps the original.

    0 讨论(0)
提交回复
热议问题