Don’t Fear Exceptions

If you’re not one of the few, you surely get scared once you see one of these:

Fatal error: Uncaught exception ‘Exception’ with message ‘Not found’ in /home/usman/www/test.php on line 27

Fatal error: Uncaught exception ‘UnexpectedValueException’ in /home/usman/www/test.php on line 27

When you see Red or Orange screen with Exception you fear like you’ve committed a sin and just go back to code to repent. Congrats, you’re the majority.

What if I told you that Exceptions are no sin, rather blessings of object oriented programming?
What if I told you that an Exception doesn’t just mean that your code is wrong?

Let me show you how.

For example code, I am using Laravel PHP framework. But the knowledge is not Laravel specific. This article assumes that you know basics of Exception and how to catch it.

An Example

I believe in practical example, so rather than preaching, I am showing you a real life example.

It is really common, when a you search for an entry in database, you check if this entry exists. If not then you show an error.

$person = Person::find($id);

if (! $person) {
    // Show message: Person not found
}

// Person found
return View::make('person.show', compact('person'));

You handle this problem with an if everywhere, why? Why don’t you just throw an exception when something doesn’t exist? Do just this:

$person = Person::findOrFail($id); // Will throw an exception if not found
return View::make('person.show', compact('person'));

In just one place catch this error. For Laravel, put this in your app/start/global.php:

App::error(function(\Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
    return 'Entry not found'; // You can show 404, or do whatever you want
});

If you’re not using Laravel then catch the exception using try-catch when you boot your application.

Advantages of Using Exceptions

An Exception is just what is not expected. Be fearless to throw an Exception whenever you think something is not expected and the function/method/application should stop executing further.

One of the big advantages of using Exception over traditional redirect, die/exit is that you separate your business logic from your transport layer(ex, HTTP).

For example, you use a direct HTTP redirect when a form validation fails. Now what if the end user is not using a browser at all, he is using your mobile app which uses the same business logic with an API? What if you’re unit testing? What if you’re firing a background job with CLI? No HTTP at all, now how?

You’re right, Exception. Create a class ValidationException which extends \Exception. And whenever a validation fails:

    throw new ValidationException('Hey kid, you forgot your name?');

Now catch this Exception:
In case of usual HTTP use, do a redirect.
In case of API, set a status code with JSON message perhaps.
In case of CLI, just dump the error message.

In the Example section above, you’ve seen another advantage. How we made our code simple and DRY(Don’t Repeat Yourself).
There are many other advantages, I’m not going over everything, please check this article if you’re not convinced.

In the end

I ask you one thing, please do yourself a favor, make use of object oriented best practices(like utilizing Exception) where it fits, you won’t regret. Our PHP community has been late in this regard, but the revolution is coming.

Please feel free to share your thoughts.

If you’re a Laravel developer then you may also like my model self-validating package with Exception – DRYVal.