这是一个非常基本的问题(我希望如此)。我所做的大部分异常处理都是使用 C# 进行的。在 C# 中,任何在 try catch 块中出错的代码都会由 catch 代码处理。例如
try
{
int divByZero=45/0;
}
catch(Exception ex)
{
errorCode.text=ex.message();
}
错误将显示在 errorCode.text 中。如果我尝试在 php 中运行相同的代码:
try{
$divByZero=45/0;
}
catch(Exception ex)
{
echo ex->getMessage();
}
catch 代码未运行。根据我有限的理解,php 需要抛出。这不是违背了错误检查的全部目的吗?这不是将 try catch 减少为 if then 语句吗?
if(除以零)抛出错误
请告诉我,我不必预测带有 throw 的 try catch 中所有可能的错误。如果我这样做,有没有办法让 php 的错误处理行为更像 c# ?
您还可以使用以下命令转换所有 php 错误设置错误处理程序() https://www.php.net/set_error_handler and 错误异常 https://www.php.net/manual/en/class.errorexception.php进入例外:
function exception_error_handler($errno, $errstr, $errfile, $errline )
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
$a = 1 / 0;
} catch (ErrorException $e) {
echo $e->getMessage();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)