When to throw an exception?

后端 未结 30 2518
后悔当初
后悔当初 2020-11-21 23:48

I have exceptions created for every condition that my application does not expect. UserNameNotValidException, PasswordNotCorrectException etc.

30条回答
  •  深忆病人
    2020-11-22 00:25

    I would say there are no hard and fast rules on when to use exceptions. However there are good reasons for using or not using them:

    Reasons to use exceptions:

    • The code flow for the common case is clearer
    • Can return complex error information as an object (although this can also be achieved using error "out" parameter passed by reference)
    • Languages generally provide some facility for managing tidy cleanup in the event of the exception (try/finally in Java, using in C#, RAII in C++)
    • In the event no exception is thrown, execution can sometimes be faster than checking return codes
    • In Java, checked exceptions must be declared or caught (although this can be a reason against)

    Reasons not to use exceptions:

    • Sometimes it's overkill if the error handling is simple
    • If exceptions are not documented or declared, they may be uncaught by calling code, which may be worse than if the the calling code just ignored a return code (application exit vs silent failure - which is worse may depend on the scenario)
    • In C++, code that uses exceptions must be exception safe (even if you don't throw or catch them, but call a throwing function indirectly)
    • In C++, it is hard to tell when a function might throw, therefore you must be paranoid about exception safety if you use them
    • Throwing and catching exceptions is generally significantly more expensive compared to checking a return flag

    In general, I would be more inclined to use exceptions in Java than in C++ or C#, because I am of the opinion that an exception, declared or not, is fundamentally part of the formal interface of a function, since changing your exception guarantee may break calling code. The biggest advantage of using them in Java IMO, is that you know that your caller MUST handle the exception, and this improves the chance of correct behaviour.

    Because of this, in any language, I would always derive all exceptions in a layer of code or API from a common class, so that calling code can always guarantee to catch all exceptions. Also I would consider it bad to throw exception classes that are implementation-specific, when writing an API or library (i.e. wrap exceptions from lower layers so that the exception that your caller receives is understandable in the context of your interface).

    Note that Java makes the distinction between general and Runtime exceptions in that the latter need not be declared. I would only use Runtime exception classes when you know that the error is a result of a bug in the program.

提交回复
热议问题