Cou*_*phy 3 php c# error-handling
这是一个非常基本的问题(我希望).我所做的大多数异常处理都是使用c#.在c#中,try catch块中出错的任何代码都由catch代码处理.例如
try
{
int divByZero=45/0;
}
catch(Exception ex)
{
errorCode.text=ex.message();
}
Run Code Online (Sandbox Code Playgroud)
该错误将显示在errorCode.text中.如果我尝试在php中运行相同的代码但是:
try{
$divByZero=45/0;
}
catch(Exception ex)
{
echo ex->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
捕获代码未运行.根据我的理解,php需要一个抛出.这不是打败错误检查的全部目的吗?这不会减少尝试捕获到if then语句吗?if(除以零)抛出错误请告诉我,我不必预测try中的每个可能的错误.如果我这样做,那么无论如何都要让php的错误处理更像c#吗?
您还可以使用set_error_handler()和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();
}
Run Code Online (Sandbox Code Playgroud)