如何使用Try catch

问题描述

公共类示例{

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仅在我想执行“ Exception之后的函数”时发生一次,如果Stale元素在第二次出现我想让它去异常捕获并断言断言..怎么了?

解决方法

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");
    }
}
}
,

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");
    }
}

或者您可以为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");
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...