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

后端 未结 17 1418
萌比男神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:18

    I think the difference depends on the contract of the particular class, i.e.

    For code that is meant to deal with user input, and program defensively for it (i.e. sanitise it) it would be wrong to throw an exception for invalid input - it is expected.

    For code that is meant to deal with already sanitised and validated input, which may have originated with the user, throwing an exception would be valid if you found some input that is meant to be forbidden. The calling code is violating the contract in that case, and it indicates a bug in the sanitising and/or calling code.

提交回复
热议问题