Gio*_*gio 7 php exception-handling
假设在try...catch块中有一个PHP代码.假设catch你想在内部做一些可能会失败并抛出新异常的事情(即发送电子邮件).
try {
// something bad happens
throw new Exception('Exception 1');
}
catch(Exception $e) {
// something bad happens also here
throw new Exception('Exception 2');
}
Run Code Online (Sandbox Code Playgroud)
处理catch块内异常的正确(最佳)方法是什么?
Sim*_*ast 10
根据这个答案,嵌套 try/catch 块似乎是完全有效的,如下所示:
try {
// Dangerous operation
} catch (Exception $e) {
try {
// Send notification email of failure
} catch (Exception $e) {
// Ouch, email failed too
}
}
Run Code Online (Sandbox Code Playgroud)
你不应该把任何东西扔进去catch。如果这样做,那么您可以省略 try-catch 的内层并在 try-catch 的外层捕获异常并在那里处理该异常。
例如:
try {
function(){
try {
function(){
try {
function (){}
} catch {
throw new Exception("newInner");
}
}
} catch {
throw new Exception("new");
}
}
} catch (Exception $e) {
echo $e;
}
Run Code Online (Sandbox Code Playgroud)
可以替换为
try {
function(){
function(){
function (){
throw new Exception("newInner");
}
}
}
} catch (Exception $e) {
echo $e;
}
Run Code Online (Sandbox Code Playgroud)