问题描述
这是一个非常基本的问题(我希望)。大多数的异常处理我做了一直用C#。在C#中,在try catch块的错误了由catch代码处理的任何代码。例如:
this is a really basic question (I hope). Most of the exception handling I have done has been with c#. In c# any code that errors out in a try catch block is dealt with by the catch code. For example
try
{
int divByZero=45/0;
}
catch(Exception ex)
{
errorCode.text=ex.message();
}
将显示在errorCode.text错误。如果我尝试在不过PHP运行相同的代码:
The error would be displayed in errorCode.text. If I were to try and run the same code in php however:
try{
$divByZero=45/0;
}
catch(Exception ex)
{
echo ex->getMessage();
}
美中不足的代码无法运行。根据我的理解limeted,PHP需要一个罚球。难道这不是打败错误检查的目的吗?这难道不是减少尝试捕捉到,如果再声明?
如果(除零)抛出错误
请告诉我,我没有预见到每一个可能的错误在尝试捕捉与抛出。如果我这样做,反正是有使PHP的错误处理行为更像C#?
The catch code is not run. Based on my limeted understanding, php needs a throw. Doesn't that defeat the entire purpose of error checking? Doesn't this reduce a try catch to an if then statement? if(dividing by zero)throw errorPlease tell me that I don't have to anticipate every possible error in a try catch with a throw. If I do, is there anyway to make php's error handling behave more like c#?
推荐答案
您也可以转换所有你的PHP错误与并的为例外:
You could also convert all your php errors with set_error_handler() and ErrorException into exceptions:
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();
}
这篇关于PHP异常处理VS C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!