脚本宝典收集整理的这篇文章主要介绍了php – 如何在其他try catch块中处理异常?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
class CustomException extends \Exception { } class FirstClass { function method() { try { $get = external(); if (!isset($get['ok'])) { throw new CustomException; } return $get; } catch (Exception $ex) { echo 'ERROR1'; die(); } } } class SecondClass { function get() { try { $firstClass = new FirstClass(); $get = $firstClass->method(); } catch (CustomException $e) { echo 'ERROR2'; die(); } } } $secondClass = new SecondClass(); $secondClass->get();
这让我回复“ERROR1”,但我想从SecondClass收到“ERROR2”.
在FirstClass块中,try catch应该处理来自external()方法的错误.
我该怎么做?
class CustomException extends \Exception { } class FirstClass { function method() { try { $get = external(); if (!isset($get['ok'])) { throw new CustomException; } return $get; } catch (Exception $ex) { // maybe do some cleanups.. throw $ex; } } } class SecondClass { function get() { try { $firstClass = new FirstClass(); $get = $firstClass->method(); } catch (CustomException $e) { // some other cleanups throw $e; } } } $secondClass = new SecondClass(); $secondClass->get();
您可以使用set_exception_handler注册一个全局异常处理程序
set_exception_handler(function ($exception) { echo "Uncaught exception: ",$exception->getMessage(),"\n"; });
以上是脚本宝典为你收集整理的php – 如何在其他try catch块中处理异常?全部内容,希望文章能够帮你解决php – 如何在其他try catch块中处理异常?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。