views:

85

answers:

4

Exceptions are wonderful things, but I sometimes worry that I throw too many. Consider this example:

Class User {

  public function User(user){

    // Query database for user data

    if(!user) throw new ExistenceException('User not found');

  }

}

I'd argue that it makes as much sense to simply return false (or set all user data to false in this case), rather than throwing an exception.

Which do you prefer?

+1  A: 

I generally will use exceptions as a very last resort. If it is something that should never happen and the language support its, i'll use an assert of some sort (since it happening is surely a bug of some kind).

If it can be avoided, i'll prefer an error code.

There are of course some cases in some languages where you have little choice. For example, c++ constructors can have no return value, and it is probably bad to have a partially constructed object, so throwing an exception is sometimes the best option.

All in all, if you can test for the error condition and simply report the error to the caller in a non-exception based way, I'd prefer that.

Evan Teran
+4  A: 

Throw exception in exceptional circumstances.

If the condition is something you expect in the normal run of the program, check for it and report an error. Reserve exceptions for things that should never happen, or as an indication to other programmers that something unrecoverable has occurred.

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

Oded
+1  A: 

Here is my rule of thumb

  • normal program logic - use return codes and parameters
  • something out of the ordinary has happened - use an exception.

Something out of the ordinary is when servers or some other expected hardware or resource is unavailable. When an exception occurs, you want a developer or first line support alerted that something needs fixing.

James Westgate
+1  A: 

Use exceptions when something really bad or unexpected happens. Generally, you want to throw an exception when you have an unrecoverable error that can leave the state of your code in an inconsistent state. Sometimes you also want to throw an exception to halt the creation of an object when the constructor has been passed a non-valid argument (IllegalArgumentException). These are all exceptional cases.

As other comments have said, use exceptions sparingly and as a last resort. In Java, throwing an exception pauses the JVM, so you don't want to use for normal error handling as it will greatly decrease the performance of your application.

Vivin Paliath