When to Catch

When should you catch an exception? When you can do something about it. In most cases a thrown exception means something went truly wrong -- an exceptional situation. If that's not the case, should an exception really have been thrown?

When those exceptional situation happens there's probably very little you can do about it. Let the error bubble up to the very top level of your application -- the front controller or main entry point. Catch it there, log it (if appropriate), and show the user an error.

The good news is that most frameworks, if you're using one, will provide some nice tools that handle catching at the outermost layer for you.

Take a typical controller in a PHP app:

<?php
class BlogController
{
    public function singlePostAction($id)
    {
        try {
            $post = $this->postRepository->get($id);
        } catch (SomeDatabaseError $e) {
            $post = null;
        }

        return new TemplateView('posts/single', ['post' => $post]);
    }
}

The catch here will swallow an error, giving you less information to debug. It also clutters up your template: if ($post) { ... } else { ... }.

The better solution here is to let it throw. Let your framework catch the exception and log it. There's likely events or some other system you can hook into and show a custom error page or do whatever else needs to happen.

Your framework should have facilities to make error logging and catching easier. Let it do its work and keep your controllers and other internal objects nice, clean, and unnested.

#