Don't throw "Exception" in PHP

There are a few classes in PHP which are better used for inheritance only. Exception is one of them. Of course you can use/throw it, but you can run into problems.

For example you've got problems with PHPUnit. We're were running an older version of PHPUnit (3.7.*) and had the following case (extremly simplified):


namespace Tests\Liplex\Backend;

use Liplex\Backend\Internal\FancyThing;

class FancyThingTest extends BaseRequestTest  
    public function testMyFunction()

        $request = new FancyThing();
        $request->methodWithFaultyParameter([], null);

Calling the methodWithFaultyParameter with faulty parameters (which we do here with null) will throw Exception which we want to test here.

So far so good, the test runs, throws the Exception and everything is fine. But now in development someone moved the class FancyThing from Namespace Liplex\Backend\Internal to Liplex\Backend\External.

When the test runs now, it still passes. Why? Because there's a "class not found error" thrown which is caught by PHPUnit as an Exception.

Fortunately that doesn't work with new versions of PHPUnit (4.*) anymore. So don't throw Exception and keep your components up to date.

comments powered by Disqus