Why are Exceptions said to be so bad for Input Validation?

后端 未结 17 1372
萌比男神i
萌比男神i 2020-11-30 20:37

I understand that \"Exceptions are for exceptional cases\" [a], but besides just being repeated over and over again, I\'ve never found an actual reason for this fact.

<
17条回答
  •  北海茫月
    2020-11-30 21:19

    Errors and Exceptions – What, When and Where?

    Exceptions are intended to report errors, thereby making code more robust. To understand when to use exceptions, one must first understand what errors are and what is not an error.

    A function is a unit of work, and failures should be viewed as errors or otherwise based on their impact on functions. Within a function f, a failure is an error if and only if it prevents f from meeting any of its callee’s preconditions, achieving any of f’s own postconditions, or reestablishing any invariant that f shares responsibility for maintaining.

    There are three kinds of errors:

    • a condition that prevents the function from meeting a precondition (e.g., a parameter restriction) of another function that must be called;
    • a condition that prevents the function from establishing one of its own postconditions (e.g., producing a valid return value is a postcondition); and
    • a condition that prevents the function from re-establishing an invariant that it is responsible for maintaining. This is a special kind of postcondition that applies particularly to member functions. An essential postcondition of every non-private member function is that it must re-establish its class’s invariants.

    Any other condition is not an error and should not be reported as an error.

    Why are Exceptions said to be so bad for Input Validation?

    I guess it is because of a somewhat ambiguous understanding of “input” as either meaning input of a function or value of a field, where the latter should’t throw an exception unless it is part of a failing function.

提交回复
热议问题