Selenium - Throwable没有捕获异常

时间:2014-03-18 04:01:19

标签: selenium nullpointerexception throwable

我正在尝试在下面给出的代码中使用throwable类&由于某种原因,它在特定情况下没有捕获异常。 我的测试用例是在安全搜索模式开启后验证Google搜索页面上的特定文本。所以基本上我正在使用该位置的Xpath将文本“安全搜索”(我们通常在Google页面上的“设置”按钮旁边,如果安全搜索处于打开状态)与该位置的X路匹配。我正在使用断言。 当系统上存在“安全搜索”文本时,我的测试用例就可以正常运行了。当实际与实际不匹配时预期的字符串值。但是,当未列出文本时,执行后Catch块不会捕获异常。 我的代码在尝试使用xpath查找文本时会陷入困境。一旦我手动关闭浏览器,它就会收到消息'Text Not Matched - Null'。 我期待浏览器关闭&在输出中我应该得到Null异常。在这种情况下,有人可以帮助我吗? 这是我的代码片段

String S1 = "//*[@id='ab_ctls']/li[1]/span";
String S2 = "SafeSearch On";
System.out.println("Test before search");
try {
Assert.assertEquals(d1.findElement(By.xpath(S1)).getText(),S2);
System.out.println("Text Matched");
} catch (Throwable e){
System.out.println("Text not Matched"+"---"+ e.getmessages());
} 
d1.quit();

1 个答案:

答案 0 :(得分:1)

Throwable会抓住所有内容。你应该捕获异常而不是throwable,因为使用throwable你会捕获异常加上错误。

try{
//....
}catch (Exception e){
// Do Something
}

Java中的异常层次结构

enter image description here

这将有助于Why catch Exceptions in Java, when you can catch Throwables?