When to throw exceptions?

Exceptions are wonderful things, but I sometimes fear that I will throw too much. Consider this example:

Class user {

public function User(user){ // Query database for user data if(!user) throw new ExistenceException('User not found'); } 

}

I would argue that it makes sense to simply return false (or set all user data to false in this case), and not throw an exception.

What do you prefer?

+2
source share
4 answers

Throw an exception in exceptional circumstances.

If you expect this condition in a regular program run, check it and report an error. Reserve exceptions for things that should never happen, or as an indication to other programmers that something unrecoverable has happened.

In your case, returning false makes sense (or perhaps use a null object as the return value).

+4
source

I usually use exceptions as a last resort. If this is something that should never happen, and the language supports it, I will use some kind of statement (since this happens, of course, it is some mistake).

If this can be avoided, I will prefer the error code.

Of course, there are some cases in some languages ​​where you have little choice. For example, C ++ constructors cannot have any return value, and it is probably bad to have a partially constructed object, so it is sometimes preferable to throw an exception.

In general, if you can test the error condition and just report the error to the caller in a way other than the exception, I would prefer this.

+1
source

Here is my rule of thumb

  • normal program logic - use return codes and parameters
  • something unusual happened - use an exception.

Something unusual is when servers or other expected equipment or resources are unavailable. When an exception occurs, you want the developer or the first line to support a warning that something needs to be fixed.

+1
source

Use exceptions if something really bad or unexpected happens . Typically, you want to throw an exception if you have a fatal error that could leave your code in an inconsistent state . Sometimes you also want to throw an exception to stop the object from being created when an invalid argument (IllegalArgumentException) was passed to the constructor. All these are exceptional cases.

As other comments point out, use exceptions sparingly and as a last resort. In Java, throwing an exception pauses the JVM, so you do not want to use it for normal error handling, as this will significantly reduce the performance of your application.

+1
source

All Articles