假设我有一个(非常简单的)递归方法,如下所示:
public static void myMeth(int n)
{
// do something
// now execute the recursive call
if (n < 0) return;
else if ( n == SOME_CONST ) throw new UnsupportedOperationException();
else myMeth(n - 1);
}
(第二个条件n == SOME_CONST
只是为了表明有时会发生异常,有时不会)。
假设我调用 myMeth(10)
,并且在几次递归调用后确实发生了异常(例如 SOME_CONST == 5
)。
我可以采取什么技巧(即使用 try-catch
block )让我回到 myMeth
的第一帧吗?
最佳答案
这可行,可能有一个更干净的解决方案,但这只是一个开始:
public static void myMeth(int n, boolean firstCall)
{
// do something
// now execute the recursive call
try
{
if (n < 0) return;
else if ( n == SOME_CONST ) throw new UnsupportedOperationException();
else myMeth(n - 1, false);
}
catch(UnsupportedOperationException e)
{
if (firstCall)
{
//logic
}
else
{
throw e;
}
}
}
关于java - 展开到 Java 中递归调用的第一帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21171274/