Skip to main content
2 of 3
added 12 characters in body
Andy
  • 2k
  • 16
  • 22

I'm going to take a slightly different track (I hope) than the other answers. A method should throw an exception when it's unable to fulfill its contract, which is based on how you name the method. The other answers say "exceptions for exception conditions," which I think can lead to some questionable design choices in some situations. There are times where it can be hard to say if something which happens during the execution of a method should be rare (and thus exception) or a normal result path. Thinking about "did the method perform what its intended function" helps clarify things, IMO.

So a ValidateLotteryTicket method should return a result if the ticket is a winner, if its not a winner, or if the ticket number is invalid. It should throw an exception if something prevents it from actually validating the ticket, perhaps due a network error, the host process is shutting down, or the host machine is out of memory to continue. The validate method should only return if it was able to perform the validation and come to a conclusion.

A method to Login should throw if it is unable to log the user in; again, perhaps there's a network error preventing the credential validation, maybe the account is locked, maybe the password is invalid, or even the system was unable to log a login audit record after successfully validating the credentials. The expectation when Login is called and returns is that the user is now logged in with appropriate privileges assigned. If Login cannot exit in that state, it should throw an exception.

Andy
  • 2k
  • 16
  • 22