PHP check thrown exception type

半腔热情 提交于 2019-12-18 18:42:02

问题


Of course in PHP you can catch all thrown exceptions with:

try{
    /* code with exceptions */
}catch(Exception $e) {
    /* Handling exceptions */
}

But is there a way to check the exception type of the thrown exception from inside the catch block?


回答1:


You can use get_class:

try {
    throw new InvalidArgumentException("Non Sequitur!", 1);
} catch (Exception $e) {
    echo get_class($e);
}



回答2:


You can have multiple catch blocks to catch different Exception types. See below:

try {
    /* code with exceptions */
} catch (MyFirstCustomException $e) {
    // We know it is a MyFirstCustomException
} catch (MySecondCustomException $e) {
    // We know it is a MySecondCustomException
} catch (Exception $e) {
    // If it is neither of the above, we can catch all remaining exceptions.
}

You should know that once an Exception is caught by a catch statement, none of the following catch statements will be triggered, even if they match the Exception.

You can also use the get_class method to get the full class name of any object, including Exceptions.



来源:https://stackoverflow.com/questions/38316800/php-check-thrown-exception-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!