Why Re-throw Exceptions?

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

    Sometimes you want to hide the implementation details of a method or improve the level of abstraction of a problem so that it’s more meaningful to the caller of a method. To do this, you can intercept the original exception and substitute a custom exception that’s better suited for explaining the problem.

    Take for example a method that loads the requested user’s details from a text file. The method assumes that a text file exists named with the user’s ID and a suffix of “.data”. When that file doesn’t actually exist, it doesn’t make much sense to throw a FileNotFoundException because the fact that each user’s details are stored in a text file is an implementation detail internal to the method. So this method could instead wrap the original exception in a custom exception with an explanatory message.

    Unlike the code you're shown, best practice is that the original exception should be kept by loading it as the InnerException property of your new exception. This means that a developer can still analyze the underlying problem if necessary.

    When you're creating a custom exception, here's a useful checklist:

    • Find a good name that conveys why the exception was thrown and make sure that the name ends with the word “Exception”.

    • Ensure that you implement the three standard exception constructors.

    • Ensure that you mark your exception with the Serializable attribute.

    • Ensure that you implement the deserialization constructor.

    • Add any custom exception properties that might help developers to understand and handle your exception better.

    • If you add any custom properties, make sure that you implement and override GetObjectData to serialize your custom properties.

    • If you add any custom properties, override the Message property so that you can add your properties to the standard exception message.

    • Remember to attach the original exception using the InnerException property of your custom exception.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 00:52

    THE MAIN REASON of re-throwing exceptions is to leave Call Stack untouched, so you can get more complete picture of what happens and calls sequence.

    0 讨论(0)
  • 2020-12-13 01:00

    You typically catch and re-throw for one of two reasons, depending on where the code sits architecturally within an application.

    At the core of an application you typically catch and re-throw to translate an exception into something more meaningful. For example if you're writing a data access layer and using custom error codes with SQL Server, you might translate SqlException into things like ObjectNotFoundException. This is useful because (a) it makes it easier for callers to handle specific types of exception, and (b) because it prevents implementation details of that layer such as the fact you're using SQL Server for persistence leaking into other layers, which allows you to change things in the future more easily.

    At boundaries of applications it's common to catch and re-throw without translating an exception so that you can log details of it, aiding in debugging and diagnosing live issues. Ideally you want to publish error somewhere that the operations team can easily monitor (e.g. the event log) as well as somewhere that gives context around where the exception happened in the control flow for developers (typically tracing).

    0 讨论(0)
  • 2020-12-13 01:01

    FYI, this is a related question about each type of re-throw: Performance Considerations for throwing Exceptions

    My question focuses on "Why" we re-throw exceptions and its usage in application exception handling strategy.

    0 讨论(0)
  • 2020-12-13 01:04

    Until I started using the EntLib ExceptionBlock, I was using them to log errors before throwing them. Kind of nasty when you think I could have handled them at that point, but at the time it was better to have them fail nastily in UAT (after logging them) rather than cover a flow-on bug.

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