PHP try catch exceptions

主宰稳场 提交于 2020-01-02 02:01:07

问题


Hello I have a code like that :

try
{
    // Here I call my external function
    do_some_work()
}
catch(Exception $e){}

The question is: If the do_some_work() has a problem and produce an Error this try catch will hide the error?


回答1:


There are two types of error in PHP. There are exceptions, and there are errors.

try..catch will handle exceptions, but it will not handle errors.

In order to catch PHP errors, you need to use the set_error_handler() function.

One way to simplify things mught be to get set_error_handler() to throw an exception when you encounter an error. You'd need to tread carefully if you do this, as it has the potential to cause all kinds of trouble, but it would be a way to get try..catch to work with all PHP's errors.




回答2:


If do_some_work() throws an exception, it will be catched and ignored.

The try/catch construct has no effect on standard PHP errors, only on exceptions.




回答3:


produce a Fatal Error

No, catch can not catch Fatal Errors. You can not even with an error handler.

If you want to catch all other errors, have a look for ErrorException and it's dedicated use with set_error_handler:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();


来源:https://stackoverflow.com/questions/7723903/php-try-catch-exceptions

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