Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

php - Can't catch symfony FatalErrorException

I have code like this:

try {
    $var = $object->getCollection()->first()->getItem()->getName();
} catch(Exception $e) {
    $var = null;
}

Of course i have communicative variable and method names. This is just demonstration.

So if my collection is empty the Collection::first() will return false. Then the getItem call will throw a SymfonyComponentDebugExceptionFatalErrorException which won't be catched by the code above.

My question is that how can i catch this exception? I have long chains like this with many getters that can return null. So i prefer this way rather than checking every value for null.

question from:https://stackoverflow.com/questions/28406566/cant-catch-symfony-fatalerrorexception

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Throwable class instead Exception class:

try {
    $var = $object->getCollection()->first()->getItem()->getName();
} catch(Throwable $e) {
    $var = null;
    $msg = $e->getMessage();
}

Since PHP 7.0 exceptions thrown from fatal and recoverable errors are instances of a new and separate exception class: Error. This new Error class implements Throwable interface, which specifies methods nearly identical to those of Exception. Because Throwable is higher in hierarchy you can catch with it both, Error and Exception.

interface Throwable
|- Exception implements Throwable
    |- ...
|- Error implements Throwable
    |- TypeError extends Error
    |- ParseError extends Error
    |- ArithmeticError extends Error
        |- DivisionByZeroError extends ArithmeticError
    |- AssertionError extends Error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...