我想在我的代码的一部分中使用异常来处理错误,但如果代码失败,我希望脚本继续。我想记录错误。有人可以帮我解决这个问题吗?
try{
if($id == 4)
{
echo'test';
}
}
catch(Exception $e){
echo $e->getMessage();
}
echo'Hello, you should see me...'; <------ I never see this.. No errors, just a trace.
答案 0 :(得分:5)
你必须抓住例外:
// some code
try {
// some code, that might throw an exception
// Note that, when the exception is thrown, the code that's after what
// threw it, until the end of this "try" block, will not be executed
} catch (Exception $e) {
// deal with the exception
// code that will be executed only when an exception is thrown
echo $e->getMessage(); // for instance
}
// some code, that will always be executed
以下是您应该阅读的一些内容:
答案 1 :(得分:2)
在调用的代码中可能抛出Exception的代码
try {
// code that may break/throw an exception
echo 'Foo';
throw new Exception('Nothing in this try block beyond this line');
echo 'I am never executed';
throw new CustomException('Neither am I');
} catch(CustomException $e) {
// continue here when any CustomException in try block occurs
echo $e->getMessage();
} catch(Exception $e) {
// continue here when any other Exception in try block occurs
echo $e->getMessage();
}
// script continues here
echo 'done';
输出将是(为便于阅读添加换行符):
'Foo' // echoed in try block
'Nothing in this try block beyond this line' // echoed in Exception catch block
'done' // echoed after try/catch block
Try / Catch Blocks也可以嵌套。请参阅上面链接的PHP手册页中的示例2:
try{
try {
throw new Exception('Foo');
echo 'not getting here';
} catch (Exception $e) {
echo $e->getMessage();
}
echo 'bar';
} catch (Exception $e) {
echo $e->getMessage();
}
echo 'done';
'Foo' // echoed in inner catch block
'bar' // echoed after inner try/catch block
'done' // echoed after outer try/catch block
DevZone的进一步阅读: