简体   繁体   English

为什么在try-catch中包装的PHP代码上出现错误?

[英]Why am I getting errors thrown on PHP code wrapped in a try-catch?

<?php

try {   
    $attrs = $xml->attributes();
    $code = $attrs['_Code'];
}
catch (Exception $e)  
{
    $code = '';
}

?>

Gets me: 得到我:

Fatal error: Call to a member function attributes() on a non-object on line 6 致命错误:在第6行的非对象上调用成员函数attribute()

Why am I getting errors thrown on code wrapped in a try-catch?? 为什么在try-catch中包装的代码上引发错误?


NOTE: It is possible to avoid this error by using the following code. 注: 可以通过使用下面的代码来避免这个错误。 (The question is not about avoiding the error, but why it's not being caught- still I thought I'd share the non-erroring code anyway) (问题不是关于避免错误,而是为什么它没有被捕获-我仍然认为我仍然会共享无错误的代码)

if (is_object($xml) && method_exists($xml,'attributes')) {
    $attrs = $xml->attributes();
    $code = !empty($attrs['_Code'])?$attrs['_Code']:'';
 }
else {
    $code = '';
}

PHP fatal errors cannot be caught. 无法捕获PHP致命错误。 I don't know the specifics of what you're doing, but you'll have to figure out some other way to test whether $xml->attributes() will work or not. 我不知道您正在执行的操作的细节,但是您将不得不找出其他方法来测试$xml->attributes()是否有效。

Also, swallowing every error and not logging it anywhere is bad practice because when stuff starts breaking you won't have any idea of why. 同样,吞并每个错误而不在任何地方记录它都是不好的做法,因为当东西开始破裂时,您将不知道为什么。

try / catch only works for exceptions , not parse errors. try / catch仅适用于异常 ,不适用于解析错误。 You have to test to make sure that $xml has an attributes method to avoid such an error (could be called a null pointer, but not exactly). 您必须进行测试以确保$xml具有避免这种错误的attributes方法(可以称为空指针,但不完全是)。

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

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