简体   繁体   English

PHP Try / Catch块暂停代码执行

[英]PHP Try/Catch block halting code execution

I'm running the following code: 我正在运行以下代码:

    try {

        $count = $user[0]->followers_count;

    } catch (Exception $e) {

        return 'error';
    }

    dd('continuing execution');

Which outputs this: 输出以下内容:

FatalErrorException in Twitter.php line 174: Cannot use object of type stdClass as array Twitter.php第174行中的FatalErrorException:无法将类型为stdClass的对象用作数组

Now, a quote from https://stackoverflow.com/a/13955721/2724978 现在,引用来自https://stackoverflow.com/a/13955721/2724978

First of all one should make clear that an exception is only fatal if it is not caught. 首先,应该明确指出,只有在未捕获到异常的情况下,它才是致命的。 Catching an exception does not halt script execution. 捕获异常不会停止脚本执行。

My code is not continuing the execution even though it's on a try/catch block. 我的代码即使在try / catch块中,也无法继续执行。 I'm pretty sure I'm missing something, what is it? 我很确定我缺少什么,那是什么?

Well, the answer I found is that in PHP, Errors and Exceptions are different things.. Exceptions can be caught and code will not halt. 好吧,我发现的答案是在PHP中,错误和异常是不同的东西。可以捕获异常,并且代码不会停止。 Errors such as FatalErrorException, on the other hand, will always halt the application even if it's in a try/catch block. 另一方面,诸如FatalErrorException之类的错误将始终停止应用程序,即使该应用程序位于try / catch块中也是如此。

No way around it, have to write code for checking variable types. 没办法,必须编写代码来检查变量类型。

Also, another thing.. Sometimes (in laravel for example) you gotta use \\Exception instead of just Exception. 另外,另一件事..有时(例如在laravel中),您必须使用\\ Exception而不是Exception。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM