Java知识23 异常处理【多测师】

一、Java异常处理
1.写代码时非法的输入
2.要打开的文件不存在
3.网络通信时连接中断,或者JVM内存溢出

二、Exception类
所有的异常类都是Java.lang.Exception类继承的子类
Exception类和Error类是Throwable类的子类 
异常类有俩个主要的子类:IOException和RuntimeException类

三、Java定义了异常类在Java.lang标准包当中
四、异常方法
五、捕获异常
使用try和catch关键字可以捕获异常 
基本语法如下:
try
{
   // 程序代码
}catch(ExceptionName e1)
{
   //Catch 块
}

举列子:
@AfterSuite
  public void closeSession() {

   if (driver.getPageSource().contains("取消")) {

    IOSElement cancelButton = driver.findElement(By.name("取消"));
    methods.Methods.myclick(cancelButton);

    try {
     Thread.sleep(1000);
    } catch (InterruptedException e) {

     e.printStackTrace();
    }

   }

   driver.quit();
六、catch语句包含要捕获异常类型的声明,当代码块中发生一个异常时,try后面的catch块就会被检查 如果发生的异常包含在catch块中,异常会被传递到catch块。
声明俩个元素的一个数组,访问第三个元素时会抛异常
public class ExcepTest{ 
    public static void main(String args[]){ 
        try{ 
            int a[] = new int[2]; 
            System.out.println("Access element three :" + a[3]); 
        }catch(ArrayIndexOutOfBoundsException e){                                              
            System.out.println("Exception thrown :" + e);
        }
        System.out.println("Out of the block"); 
    }
}

七、多重捕获
一个try代码块后面跟随多个catch代码块叫做多重捕获
保护代码块发生异常先抛给第一个catch块、第二个catch块、直到异常通过所有的catch块

八、可用throws和throw关键字声明 捕获一个检查性异常
九、finally关键字 
无论是否发生异常 finally代码块中的代码总会被执行
十、catch不能独立于try存在
try catch finally块之间不能添加任何代码
十一、自定义异常
写一个检查性异常类 需要继承Exception类
写一个运行时异常类 需要继承RuntimeException类
实例如下:
//自定义异常类,继承Exception类
public class InsufficientFundsException extends Exception
{
//此处的amount用来储存当出现异常(取出钱多于余额时)所缺乏的钱
private double amount;
public InsufficientFundsException(double amount)
{
 this.amount = amount;
}
public double getAmount()
{
 return amount;
}
}

 

posted @ 2020-06-12 22:39  多测师_王sir  阅读(118)  评论(0编辑  收藏  举报