-1

公共类样本{

public static void main(String[] args) {

    method();

}

public static void method()
{
    try {
        System.out.println("function");
        throw new StaleElementReferenceException("thih sexception occured");
    }
    catch (StaleElementReferenceException e) {
        method();
    }
    catch (Exception e) {
        System.out.println("AssertFail");
    }
}

}

如何使用 Try catch 在非返回方法中避免无限递归...例如下面的代码...当 StaleElementException 仅发生一次我想执行“异常之后的函数,如果过时元素第二次出现我想要它去异常捕获并打印断言失败..如何?

4

2 回答 2

0
public class Sample {

public static void main(String[] args) {

    method(false);

}

public static void method(boolean calledFromCatchBlock)
{
    try {
        System.out.println("function");
        if(!calledFromCatchBlock) {
            throw new StaleElementReferenceException("thih sexception occured");
        } else {
            throw new Exception();
        }
    } catch (StaleElementReferenceException e) {
        method(true);
    } catch (Exception e) {
        System.out.println("AssertFail");
    }
}
}
于 2020-09-09T18:28:33.750 回答
0

当您在外面抛出异常(例如boolean标志)时,您应该以某种方式存储状态method(),检查此状态并下次抛出修改后的异常:

private static boolean alreadyThrown = false;

public static void method()
{
    try {
        System.out.println("function");
        if (alreadyThrown) {
            throw new RuntimeException("another exception occured");
        } else {
            alreadyThrown = true;
            throw new StaleElementReferenceException("this exception occured");
        }
    }
    catch (StaleElementReferenceException e) {
        method();
    }
    catch (Exception e) {
        System.out.println("AssertFail");
    }
}

或者您可以为 the 提供一些参数method(int arg)并以类似的方式检查其值:

public static void main(String[] args) {
    method(1);
}

public static void method(int arg)
{
    try {
        System.out.println("function");
        if (arg > 1) {
            throw new RuntimeException("another exception occured");
        } else {
            throw new StaleElementReferenceException("this exception occured");
        }
    }
    catch (StaleElementReferenceException e) {
        method(arg + 1);
    }
    catch (Exception e) {
        System.out.println("AssertFail");
    }
}
于 2020-09-09T18:37:38.407 回答