Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return early on error or throw an exception?

I usually indicate an error in a method by returning false, but it doesn't always gel with me semantically (as depending on the method, false may be a valid return).

I've looked into exceptions, and am wondering are they a one-size-fits-all solution? Should I return false where I can still?

I may be completely missing the point here so please bear with me.

// My old way
function getProductById($id) {

    if ( ! is_numeric($id)) {
         return false;     
    }

}

// My consideration
function getProductById($id) {

    if ( ! is_numeric($id)) {
         throw new Exception('The id must be numerical!');     
    }

}
like image 665
alex Avatar asked Oct 14 '25 03:10

alex


1 Answers

My train of thought is this:

If a piece of code can't do its work because a pre-condition failed, throw an exception.

So, if your getProductById() method wasn't provided with the correct type of value to be able to do what it's supposed to, that's a reason to throw an exception.

This allows you to spot problems much quicker, because of the clear distinction between "no result" and "potentially invalid state". It gives you peace of mind, if you get used to throwing an exception in such cases, because it'll fail hard instead of going on in an undefined / unexpected way.

I'd return false or null, if everything worked as it was supposed to (as defined), but the process just didn't find a matching product.

P.S.: That's also why throwing exceptions from input validation is wrong per my definition. The whole purpose of the code was to validate the inputs, so invalid inputs are to be expected and thus not exceptional.

like image 64
DanMan Avatar answered Oct 18 '25 06:10

DanMan