异常的捕获要通过try--catch--finally语句块来完成:
1.try是不可缺少额语句块,主要用来放置可能出现异常的语句;
2.catch和finally两者至少要有一个1个与try配套;
3.catch块是用来放置异常发生后的处理语句;
4.finally里放置的则是无论发生异常与否都会执行的语句。
注:对异常进行捕获会占用很高的内存,因此try块中的语句要尽量少。
try--catch--finally的执行顺序:
实例代码:
package com.xhj.exception;
/**
* 认识try--catch--finally的执行顺序
*
* @author XIEHEJUN
*
*/
public class ExecuteExceptionShort {
public static void main(String[] args) {
String[] strs = new String[5];
try {
int i = strs.length;
System.out.println("----进入try代码块----");
System.out.println("String数组大小为:" + i);
String str = "我是丑小鸭!";
strs[5] = str;
System.out.println("strs[5] = " + strs[5]);
System.out.println("----离开try代码块----");
} catch (Exception e) {
System.out.println("----进入catch代码块----");
System.out.println("异常为: " + e.toString());
System.out.println("----离开catch代码块----");
} finally {
System.out.println("----进入finally代码块----");
strs[4] = "我是美丽的白天鹅";
System.out.println(strs[4]);
System.out.println("----离开finally代码块----");
}
}
}
注:try--catch--finally语句块可捕获多个异常,但是在捕获多个异常的时候一定要注多个catch的执行顺序,
所要捕获的异常一定要从小到大排列。当然也可直接通过所有异常的父类Exception,来简单处理。
1.Exception NoSuchElementException:
解决方法:
1)检查目标element的locator
2)如果locator是正确的,尝试在查找element之前等待页面的加载
3)如果等待了很久也一直没有找到element,尝试使用另外一个locator
2.Exception NoSuchWindowException
解决方法:
1)检查窗口的locator
2)在找窗口之前,等到页面的加载
3.Exception NoAlertPresentException
解决方法:
1)确认alert(javascript 顶层的窗口,不是最新的)是当前的
2)在操作alert之前等待页面的加载
4.Exception NoSuchFrameException
解决方法:
1)检查frame的locator
2)检查这个frame是否有一些父frame(如果有父frame的话,应该先转换到父frame)
3)在转换到目标frame之前,确认转换到了默认的content(仅有一个frame)
4)在转换frame之前等待页面的加载
5.Exception UnhandledAlertException
解决方法:
try catch
6.Exception UnexpectedTagNameException
解决方法:
try catch
7.Exception StaleElementReferenceException
解决方法:
try catch
8.Exception TimeoutException
解决方法:
try catch