When to throw an exception?

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

    Ultimately the decision comes down to whether it is more helpful to deal with application-level errors like this using exception handling, or via your own home-rolled mechanism like returning status codes. I don't think there's a hard-and-fast rule about which is better, but I would consider:

    • Who's calling your code? Is this a public API of some sort or an internal library?
    • What language are you using? If it's Java, for example, then throwing a (checked) exception puts an explicit burden on your caller to handle this error condition in some way, as opposed to a return status which could be ignored. That could be good or bad.
    • How are other error conditions in the same application handled? Callers won't want to deal with a module that handles errors in an idiosyncratic way unlike anything else in the system.
    • How many things can go wrong with the routine in question, and how would they be handled differently? Consider the difference between a series of catch blocks that handle different errors and a switch on an error code.
    • Do you have structured information about the error you need to return? Throwing an exception gives you a better place to put this information than just returning a status.

提交回复
热议问题