1

假设我有一个(非常简单)这样的递归方法:

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让我回到第一帧myMeth吗?

4

5 回答 5

1

这可能有效,可能有一个更清洁的解决方案,但这是一个开始:

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;
         }
     }
}
于 2014-01-16T19:53:22.030 回答
0
try{

     myMeth(n);

catch (UnsupportedOperationException e) {
 myMeth(n); //or another number
}
于 2014-01-16T19:47:02.757 回答
0
// depth should be 0 on first call
public static boolean myMeth(int n, int depth)
{
     // do something

     // now execute the recursive call
     if (n < 0) return true;
     else if ( n == SOME_CONST ) return false;
     boolean success = myMeth(n - 1, depth + 1);
     if (depth == 0 && !success) {
         // uh-oh
     }
     return success;
}

或者,如果您不关心递归中的每个单独帧,请depth用布尔值替换并更改为boolean success = myMeth(n - 1, false);

不过,当您说要回到第一帧时,我不确定您在问什么。您想回到第一个方法调用的开头,以便重复// do something块中的步骤吗?或者你在递归调用之后执行得很myMeth好吗?

如果您Exception自己生成,我使用布尔值代替了对它的需求。如果没有,您可以更换它。您也可以在第一帧中抛出异常,同时仍然使用布尔值。

于 2014-01-16T20:12:59.330 回答
0

使用另一个静态变量来跟踪第一个数字 (10)

    static int SOME_CONST = 5;
    static int keepN;

    public static void myMeth(int n) {
        // do something

        // now execute the recursive call
        try {
            if (n < 0) {
                return;
            } else if (n == SOME_CONST) {
                throw new UnsupportedOperationException();
            } else {
                myMeth(n - 1);
            }
        } catch (UnsupportedOperationException e) {
            if (n == keepN) {
                System.out.println(e);
                System.out.println("YES first frame");
            } else {
                System.out.println("NO");
                throw e;
            }
        }
    }

    public static void main(String[] args) {
        keepN = 10;
        myMeth(10);
    }
于 2014-01-16T19:55:23.673 回答
-1

是的,但是这种技巧会错过递归的整个概念,并且很难阅读和理解。如果您不能期望它可以产生确定数量的选项,则不应使用递归。

否则使用其他解决方案。

于 2014-01-16T19:41:51.073 回答