When to throw an exception?

后端 未结 30 2014
后悔当初
后悔当初 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:33

    "PasswordNotCorrectException" isn't a good example for using exceptions. Users getting their passwords wrong is to be expected, so it's hardly an exception IMHO. You probably even recover from it, showing a nice error message, so it's just a validity check.

    Unhandled exceptions will stop the execution eventually - which is good. If you're returning false, null or error codes, you will have to deal with the program's state all by yourself. If you forget to check conditions somewhere, your program may keep running with wrong data, and you may have a hard time figuring out what happened and where.

    Of course, you could cause the same problem with empty catch statements, but at least spotting those is easier and doesn't require you to understand the logic.

    So as a rule of thumb:

    Use them wherever you don't want or simply can't recover from an error.

提交回复
热议问题