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

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

    In general, libraries throw exceptions and clients catch them and do something intelligent with them. For user input I just write validation functions instead of throwing exceptions. Exceptions seem excessive for something like that.

    There are performance issues with exceptions, but in GUI code you won't generally have to worry about them. So what if a validation takes an extra 100 ms to run? The user isn't going to notice that.

    In some ways it's a tough call - On the one hand, you might not want to have your entire application come crashing down because the user entered an extra digit in a zip code text box and you forgot to handle the exception. On the other, a 'fail early, fail hard' approach ensures that bugs get discovered and fixed quickly and keeps your precious database sane. In general I think most frameworks recommend that you don't use exception handling for UI error checking and some, like .NET Windows Forms, provide nice ways to do this (ErrorProviders and Validation events) without exceptions.

提交回复
热议问题