Exception vs Error vs Throwable

Exception and Error are 2 different special classes provided by PHP that implement Throwable interface. They are special because they can be used with throw keyword. But what's the difference and what should you use?

The answer is, as always, it depends.

public function handle(): void
{
    try {
        $x = 25 / 0;
    } catch(\Exception $e) {
        dd($e->getMessage());
    }
}

That's a silly example, but what do you think will happen on the above code? You may think that dd() inside catch will be triggered, but that's not the truth.

This is an Error and not an Exception, but it may trick you from time to time.

The correct way to catch that would be :

public function handle(): void
{
    try {
        $x = 25 / 0;
    } catch(\Error $e) {
        dd($e->getMessage());
    }
}

If you want to catch both Error and Exception, you can type hint the $e parameter, as the interface Throwable. Both classes implement that.

public function handle(): void
{
    try {
        $x = 25 / 0;
    } catch(\Throwable $e) {
       dd($e->getMessage());
    }
}

Usually Errors are not to be caught, except for logging purposes or if you execute any unknown dynamic code, where you want this extra safety. That's why you may see in on frameworks and libraries code, under the hood.

You can always read all the possible Errors on the docs https://www.php.net/manual/en/class.error.php

Exception are more proper to be caught, since they are created for that reason.

But it really depends! Knowing the differences will allow you to take the best decision for your case.

Subscribe to Lioy

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe