我在一个主try catch语句中嵌套try catch,我想知道如果其中一个嵌套的try catch失败,我怎么能使主try catch失败?
这是我的代码:
try
{
try
{
//how can I make the main try catch fail if this try catch fails?
}
catch(Exception $e)
{
error_log();
}
}
catch(Exception $e)
{
error_log();
}
答案 0 :(得分:18)
在第一个try-catch中error_log();
之后,键入throw $e;
(在新行上)。这将再次抛出错误,外部的try-catch将处理它。
答案 1 :(得分:5)
您应该为各种不同类型的Exception扩展Exception。这样你就可以触发一个特定的try-catch块:
try
{
...
try
{
throwSomeException();
}
catch ( InnerException $e )
{
...do stuff only for InnerException...
}
...
}
catch ( Exception $e )
{
...do stuff for all types of exception...
}
此外,您可以链接catch
语句以在单个try-catch中触发不同的块:
try
{
...
}
catch ( SpecificTypeOfException $e )
{
..do something specific
}
catch ( TypeOfException $e )
{
..do something less specific
}
catch ( Exception $e )
{
..do something for all exceptions
}
答案 2 :(得分:2)
在内部catch中,throw() - 不推荐,我在使用PHP时遇到过几个问题。或者设置一个标志,在内部捕获之后抛出。
以下是抛出相同异常的示例(或者您可以抛出不同的异常)。
try {
$ex = null;
try {
//how can I make the main try catch fail if this try catch fails?
} catch(Exception $e){
$ex = $e;
error_log();
}
if ($ex) {
throw $ex;
}
} catch(Exception $e){
error_log();
}
答案 3 :(得分:1)
我以类似于Javascript中的eventHandling的方式处理异常。 一个事件从特定到通用的阶梯泡沫化。当它到达启动程序时,异常会丢失它对代码的所有意义,应该只是为了记录和结束应用程序而被捕获。
与此同时,很多事情都会发生
调用堆栈:
在我吃苹果的过程中,出现了蠕虫病毒:
throw NausiaException('I found a bleeding worm...');
吃Apple范围捕获
catch(Exception $e)
异常,因为在该范围内,我们可以将苹果返回商店并向经理大喊。因为关于这一事件没有什么比这更有用了,
throw $e
因为吃苹果失败而被称为
某些事情会变得不同 但是,如果商店经理拒绝退款,您可以包装例外
throw new RefundFailedException('The manager is a cheap skate', RefundFailedException::REFUSED, $e)
开始午餐范围 开始午餐范围想要扔掉糟糕的午餐
try {
//Start lunch
} catch (Exception $e) {
switch (true) {
case $e instanceof NausiaException:
case $e instanceof RefundFailedException:
//Throw lunch away
break;
}
}
答案 4 :(得分:0)
在适当的地方使用bool变量和“return”关键字可以帮到你......