When to throw an exception?

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

    To my mind, the fundamental question should be whether one would expect that the caller would want to continue normal program flow if a condition occurs. If you don't know, either have separate doSomething and trySomething methods, where the former returns an error and the latter does not, or have a routine that accepts a parameter to indicate whether an exception should be thrown if it fails). Consider a class to send commands to a remote system and report responses. Certain commands (e.g. restart) will cause the remote system to send a response but then be non-responsive for a certain length of time. It is thus useful to be able to send a "ping" command and find out whether the remote system responds in a reasonable length of time without having to throw an exception if it doesn't (the caller would probably expect that the first few "ping" attempts would fail, but one would eventually work). On the other hand, if one has a sequence of commands like:

      exchange_command("open tempfile");
      exchange_command("write tempfile data {whatever}");
      exchange_command("write tempfile data {whatever}");
      exchange_command("write tempfile data {whatever}");
      exchange_command("write tempfile data {whatever}");
      exchange_command("close tempfile");
      exchange_command("copy tempfile to realfile");
    

    one would want failure of any operation to abort the whole sequence. While one could check each operation to ensure it succeeded, it's more helpful to have the exchange_command() routine throw an exception if a command fails.

    Actually, in the above scenario it may be helpful to have a parameter to select a number of failure-handling modes: never throw exceptions, throw exceptions for communication errors only, or throw exceptions in any cases where a command does not return a "success" indication.

提交回复
热议问题