3

As of PHP 7 it's possible to catch Fatal Errors by catching either Error class or Throwable interface, but for some reason I can't manage to do that when "Fatal Error: trait not found" is triggered.

try {
    class Cars {
        use Price;
    }
} catch (Error $e) {
    echo $e->getMessage(); // Output : Fatal error: Trait 'Price' not found in [..] on line [..]
} 

The error not caught!! So I came up with a solution

try {
    if (trait_exists('Price')) {
        class Cars{
            use Price;
        }
    } else {
        throw new Error('Trait Price not found');
    }

} catch (Error $e) {
    echo $e->getMessage(); // Output : Trait Price not found
}

Why that Fatal Error in the first example wasn't caught?

Is my approach in the second example is the only way to do it?

1
  • 7
    Why are you trying to catch that in your code? Shouldn't you know if a trait exists or not before trying to use it? If you get that error, your code is broken and you should either make sure the trait exist or remove the use from the code. Commented Aug 21, 2018 at 11:10

1 Answer 1

6

Short answer: not all errors are catchable, some are still being upgraded to the new error/exception model.

PHP 7.0 let you catch creating a missing class:

$foo = new NotAClass;

PHP 7.3 will let you catch errors about parent classes not existing (see bug #75765):

class Foo extends NotAClass {}

However, you still can't catch a missing trait (there's a note on the Github issue for the above bug about this being harder to fix):

class Foo { use NotATrait; }

Note: HHVM is apparently fine catching any and all of these, since it doesn't care what you think about the rules (and partly because this sort of thing is much easier in a fully-compiled environment).

See https://3v4l.org/L0fPA for a demo.

And yes, as was mentioned in the comments, please try and not rely on catching missing classes / traits at run-time. You should know your class hierarchy way earlier that that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.