php try 捕获致命错误,如何在PHP类型提示上捕获“可捕获的致命错误”?

更新:这不是一个可捕获的致命错误,而在php 7.而是抛出“异常”。不是从

Exception到

Error派生的“异常”(在恐慌报价中)它仍然是一个

Throwable和可以处理与正常的try-catch块。见

https://wiki.php.net/rfc/throwable-interface

例如。

class ClassA {

public function method_a (ClassB $b) { echo 'method_a: ', get_class($b), PHP_EOL; }

}

class ClassWrong{}

class ClassB{}

class ClassC extends ClassB {}

foreach( array('ClassA', 'ClassWrong', 'ClassB', 'ClassC') as $cn ) {

try{

$a = new ClassA;

$a->method_a(new $cn);

}

catch(Error $err) {

echo "catched: ", $err->getMessage(), PHP_EOL;

}

}

echo 'done.';

打印

catched: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassA given, called in [...]

catched: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassWrong given, called in [...]

method_a: ClassB

method_a: ClassC

done.

E_RECOVERABLE_ERROR ( integer )

Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also 07005), the application aborts as it was an E_ERROR.

例如

function myErrorHandler($errno, $errstr, $errfile, $errline) {

if ( E_RECOVERABLE_ERROR===$errno ) {

echo "'catched' catchable fatal error\n";

return true;

}

return false;

}

set_error_handler('myErrorHandler');

class ClassA {

public function method_a (ClassB $b) {}

}

class ClassWrong{}

$a = new ClassA;

$a->method_a(new ClassWrong);

echo 'done.';

打印

'catched' catchable fatal error

done.

编辑:但你可以“使”它是一个异常,你可以处理与try-catch块

function myErrorHandler($errno, $errstr, $errfile, $errline) {

if ( E_RECOVERABLE_ERROR===$errno ) {

echo "'catched' catchable fatal error\n";

throw new ErrorException($errstr, $errno, 0, $errfile, $errline);

// return true;

}

return false;

}

set_error_handler('myErrorHandler');

class ClassA {

public function method_a (ClassB $b) {}

}

class ClassWrong{}

try{

$a = new ClassA;

$a->method_a(new ClassWrong);

}

catch(Exception $ex) {

echo "catched\n";

}

echo 'done.';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值