lovespring
lovespring

Reputation: 440

php exception not raised of fatal error,such as "class not exist"

I suppose that the exception system of PHP will catch all. but it doesn't.

try{ 
    $obj = new Asdfasdfasdf()
} catch(Exception $e){
    trace(...something...)
}

But it doesn't catch this kind of error, and I have searched php document, which didn't say which kind of exception/error is catch-able in try,catch clause.

So, how can I know that which kind of exception/error will be catched by my catch clause ?

P.S.

I finnally understand the 'error' from php engine is not the 'exception' from use land code. If you want use exception to handle engine 'error', you should manually wrap all 'error' in exception.

Upvotes: 1

Views: 1971

Answers (1)

Darragh Enright
Darragh Enright

Reputation: 14136

If you want to throw an Exception in the event that a class does not exist it, you could use class_exists().

A naive example might look something like:

function createClass($class)
{
    if (!class_exists($class)) {
        throw new Exception(
            sprintf('Class %s does not exist', $class)
        );
    }

    return new $class;
}

try {
    $asdfasdfasdf = createClass('Asdfasdfasdf');
} catch (Exception $e) {
    echo $e->getMessage();
}

From my experience, most PHP frameworks throw some sort of exception when a class is not found - for example, Symfony2 throws a ClassNotFoundException. That said, I don't know if you can 'catch' that, it's probably really just a development aid.

PHP 7 has just been released and from what I understand from the spec, you will be able to catch a fatal error as an EngineException. I don't know if it would work for your example; I haven't tested it because I have not installed PHP 7 stable yet. I tried your example with an alpha release of PHP 7 on an online REPL, and it appears that it does not work.

However for completeness, here's an example from the RFC:

function call_method($obj) {
    $obj->method();
}

try {
    call_method(null); // oops!
} catch (EngineException $e) {
    echo "Exception: {$e->getMessage()}\n";
}

// Exception: Call to a member function method() on a non-object

In any case, as noted by @MarkBaker and @MarcB in the question's comments, you cannot "catch" a fatal error in previous versions of PHP.

Hope this helps :)

Upvotes: 1

Related Questions