java 异常处理

1.异常的分类

异常都是继承自Throwable类,有两个异常类继承自Throwable,分别为Error,Exception。

Error一般表示的Java运行时系统的内部错误和资源耗尽错误,开发时需要关注的是Exception。

Exception :又有两个分支,

                 RuntimeException(程序错误导致的异常):访问空指针,数组下标越界 

                 其他异常(程序本身没有问题,由于I/O导致的错误,如IOException):文件没有找到,根据字符串找Class对象

                                 

未检查异常:派生于Error和RuntimeException类的所有异常,应避免RuntimeException

已检查异常:未检查异常以外的其他异常,必须处理,要么抛出要么捕获处理

 

2.throws 声明抛出异常

    在遇到无法处理的情况时可以在方法的最后面用throws语句声明抛出异常,异常可以为多个,用逗号隔开

/**
     * 需要抛出异常的情况
     * 1.调用一个抛已检查异常的方法,如:new FileInputStream("a.txt");
     * 2.方法中调用了throw语句抛出 一个已检查异常
     * @throws FileNotFoundException
     */
    public void testThrows() throws FileNotFoundException ,NullPointerException {
        FileInputStream fis = new FileInputStream("a.txt");
    }

 

3.throw 抛出异常    


public class Person {  

     

  private int age;

  public int getAge() {
  return age;
  }
  /**
  * throw 的作用是抛出一个异常实例
  * 通常两种情况下会使用throw抛出异常
  * 1:当程序遇到了一个不满足业务逻辑要求的地方时,可以主动创建一个对应的异常实例,然后抛出,要求调用者解决
  * 2:当当前代码确实遇到了一个异常,但是不应当由当前代码来解决时,可以将其继续向方法外抛出由调用者解决。
  *
  * 当我们抛出了一个非RuntimeException及其子类异常时,编译器会检查我们的代码是否有处理该异常
  * 若没有处理,编译不通过。处理手段有两个:
  * 1:使用try-catch捕获该 异常并自行处理
  * 2.在当前方法上使用throws声明该异常的抛出,通知调用者来解决该异常。
  * 同样的,调用者在调用当前方法的代码那里,也可以try-catch解决或者继续向上抛出。
  *
  * 不要在main方法上声明throws
  * @param age
  * @throws Exception
  */
  public void setAge(int age) throws IllegalAgeException{

    if(age<0||age>100){
      throw new IllegalAgeException("年龄不合法");//抛出自定义异常
    }
    this.age = age;
  }


}

4.自定义异常

自定义异常只要继承Exception或者其子类即可。

public class IllegalAgeException extends Exception{

    /**
     * 
     */
    private static final long serialVersionUID = 5846248535945363760L;

    public IllegalAgeException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public IllegalAgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public IllegalAgeException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public IllegalAgeException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public IllegalAgeException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

}
public class TestIllegalException {
    public static void main(String[] args) {
        Person p = new Person();
        try {
            p.setAge(200);
        } catch (IllegalAgeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("年龄出错了");
        }
        System.out.println("p的年龄:"+p.getAge()+"岁");
    }
}

5.try-catch捕获异常机制

/**
 * java 异常捕获机制中的try-catch
 * @author lenovo
 *
 */
public class ExceptionDemo01 {
    public static void main(String[] args) {
        System.out.println("程序开始了");
        try{
            String str ="a";
            System.out.println(str.length());
            System.out.println(str.charAt(1));
            //System.out.println(Integer.parseInt(str));
            str = null;
            System.out.println(str.length());//出现空指针,跳出try
        }catch(NullPointerException  e){
            //书写出现空指针以后的处理逻辑
            System.out.println("出现了一个空指针!");
        }catch(StringIndexOutOfBoundsException  e){
            System.out.println("字符串下标越界了!");
        /**
         * 在try-catch中,catch块是可以写多个的针对不同的异常有不同处理方式时,
         * 我们就可以使用catch来捕获这些异常。
         * 但是应该有一个好的书写习惯,就是在最后一个catch捕获Exception,防止由于出现
         * 了一个未捕获的异常,导致程序中断(闪退)
         * 当多个catch中捕获的异常存在父子类继承关系时,必须保证子类异常在上,
         * 父类异常在下。
         */
        
        }catch(Exception e){                
            System.out.println("反正出了个错!");
        }
        
        System.out.println("程序结束了");
    }
}

6.finally块

/**
 * 异常捕获机制中的finally块
 * finally块必须定义在异常处理机制的最后
 * 可以直接跟在try后面,也可以跟在最后一个catch之后。
 * finally块可以保证其中的代码无论try块中的语句是否出错都会执行
 * 通常用来释放资源的操作。
 * @author lenovo
 *
 */
public class ExceptionDemo02 {
    public static void main(String[] args) {
        System.out.println("程序开始了");
        try{
            String str =null;
            System.out.println(str.length());
        }catch(Exception e){
            System.out.println("出错了");
        }finally{
            System.out.println("finally块中的代码被执行了");
        }
        System.out.println("程序结束了");
    }
}

 

posted @ 2017-05-02 14:38  月关莫利亚  阅读(331)  评论(0)    收藏  举报