When to throw an exception?

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

    Firstly, if the users of your API aren't interested in specific, fine-grained failures, then having specific exceptions for them isn't of any value.

    Since it's often not possible to know what may be useful to your users, a better approach is to have the specific exceptions, but ensure they inherit from a common class (e.g., std::exception or its derivatives in C++). That allows your client to catch specific exceptions if they choose, or the more general exception if they don't care.

提交回复
热议问题