【问题标题】:PHP Exception couldn't workPHP 异常无法工作
【发布时间】:2016-01-15 15:06:37
【问题描述】:

阅读本站 here 上的文章后,我编写了以下代码:

<?php

try{
  annundefinedmethod();
}
catch(RuntimeException $e){
  echo 'Runtime exception called';
} 
catch(BadFunctionCallException $e){
  echo 'Bad function call exception called';
}
catch(Exception $e){
  echo 'General exception called';
}

?>

我想根据 try 块中函数调用的正确异常显示错误。但是,上述所有异常都不起作用,我仍然收到一条错误消息,提示 uncaught error : call to undefined method.... 我的代码出了什么问题?

【问题讨论】:

标签: php exception exception-handling


【解决方案1】:

您无法在 PHP 中捕获致命错误。对于这种情况,您可以使用“is_callable”或“function_exists”。

如果你愿意,你可以自己投掷:

try{
    if (!is_callable('annundefinedmethod')) {
        throw new BadFunctionCallException();
    } 
}
catch(BadFunctionCallException $e){
  echo 'Bad function call exception called';
}

【讨论】:

  • 但是,try 块中的代码确实会产生错误,不是吗?那么为什么错误不能被异常自动捕获,而不必先抛出它或使用 if-else 语句检查它呢?
  • 因为这是一个致命错误。可以使用自定义错误处理程序捕获 Thay。请参阅此帖子,例如 stackoverflow.com/questions/277224/…
【解决方案2】:

很简单,未定义的方法不是引发异常的代码。

try{
  throw new Exception;
}
catch(RuntimeException $e){
  echo 'Runtime exception called';
} 
catch(BadFunctionCallException $e){
  echo 'Bad function call exception called';
}
catch(Exception $e){
  echo 'General exception called';
}

您还可以在异常中传递和调用消息,并将它们写在 catch 块中:

try{
  throw new Exception('some useful error message');
}
catch(RuntimeException $e){
  echo 'Runtime exception called';
} 
catch(BadFunctionCallException $e){
  echo 'Bad function call exception called';
}
catch(Exception $e){
  echo $e->getMessage();
}

这与您提到的其他类型的异常相同:

try{
  throw new RuntimeException;
}
catch(RuntimeException $e){
  echo 'Runtime exception called';
} 
catch(BadFunctionCallException $e){
  echo 'Bad function call exception called';
}
catch(Exception $e){
  echo 'General exception called';
}

try{
  throw new BadFunctionCallException;
}
catch(RuntimeException $e){
  echo 'Runtime exception called';
} 
catch(BadFunctionCallException $e){
  echo 'Bad function call exception called';
}
catch(Exception $e){
  echo 'General exception called';
}

【讨论】:

  • 但是,try 块中的代码确实会产生错误,不是吗?那么为什么不先抛出异常就不能自动捕获错误呢?
  • 对异常一词非常困惑。那你能给我提供自动抛出异常而不抛出异常的代码吗?
  • 在我上面提供的网站上,在第二段的“架构和最佳实践”部分中。
【解决方案3】:

在 PHP 5.x 中,您必须首先明确测试该函数是否可调用。你无法捕捉到这种类型的错误。

在 PHP 7 中,像这样的错误实际上是实现 ThrowableError 对象。 Error 是新的 PHP 7 新基类,用于抛出内部 PHP 错误。

在这种特殊情况下,您实际上得到了一个实现ThrowableError 对象。如果您在其中一种类型上添加catch,您将能够捕获此错误。

try {
    annundefinedmethod();
}
catch (Error $e) {
    //$e->getMessage() == "Call to undefined function annundefinedmethod()"
}

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 1970-01-01
    • 2019-01-13
    • 2021-08-16
    • 2012-10-28
    • 2013-10-13
    • 2012-12-06
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多