微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Try catch

如何解决如何使用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");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?