Day6—异常处理

异常体系

异常体系结构
Error

Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性的代码进行处理。

    public static void main(String[] args) {
        // error:
        // 栈溢出 java.lang.StackOverflowError
        main(args);
        
        // 堆溢出 java.lang.OutOfMemoryError
        Integer[] arr = new Integer[1024*1024*1024];    
    }
Exception

其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:

  • 空指针访问
  • 试图读取不存在的文件
  • 网络连接中断
  • 数组角标越界

Exception可分为编译时异常与运行时异常

编译时异常(受检异常):

  • 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。
  • 对于这类异常,如果程序不处理,可能会带来意想不到的结果。

运行时异常(非受检异常):

  • 是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
  • 对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。

常见异常

空指针异常 NullPointerException
@Test
    public void test1(){
        int[] arr = null;
        int num = arr[1];
    }
数组/字符串角标越界 ArrayIndexOutOfBoundsException / StringIndexOutOfBoundsException
@Test
    public void test2(){
        String str = "abc";
        char c = str.charAt(3);
    }
    
类转换异常 ClassCastException
    @Test
    public void test3(){
        Object obj = new Date();
        String str = (String)obj;
    }
数学运算异常 ArithmeticException
@Test
    public void test4(){
        int i = 10;
        int j = 0;
        int num = i / j;
    }
数字格式化异常 NumberFormatException
@Test
    public void test5(){
        String s = "abc";
        int num = Integer.parseInt(s);
        System.out.println(num);
    }

异常处理1:try-catch-finally

java异常处理采用“抓抛模型”:

  • 过程一,抛:程序正常执行过程中,一旦出现异常,就会在异常代码处生成一个对应的异常对象并将此对象抛出。一旦抛出对象以后,其后的代码不再执行
  • 过程二,抓:异常处理的方式 try_catch_finally 或 throws
  try{
  
        // 可能出现异常的代码
  
  }catch(异常类型1 变量名1){
  
        // 处理异常的方式1
  
  }catch(异常类型2 变量名2){
  
        // 处理异常的方式2
  }
  ...
  finally{
  
        // 一定会执行的代码
  
  }

try_catch:

  • 1、finally是可选的
  • 2、使用try将可能出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象根据此对象的类型,去catch中进行匹配
  • 3、一旦try中的异常对象匹配到某一个catch时,就进入到catch中进行异常处理。一旦处理完成,就跳出当前的try-catch结构(在没有finally的情况下)。继续执行其后的代码
  • 4、catch中的异常类型如果没有子父类关系,则其声明顺序没有要求;catch中的异常类型如果有子父类关系,则要求子类一定在父类上面,否则会报错
  • 5、常用的异常对象处理的方式:
    - sysout String
    - getMessage()
    - printStackTrace()
  • 6、 在try结构中声明的变量,出了try结构以后便无法继续使用

finally:

  • 1、finally是可选的
  • 2、finally中声明的是一定会执行的代码。即使catch中又出现异常,又或者try、catch中出现return语句等情况
  • 3、数据库连接、输入输出流、网络编程中的socket资源等,jvm是无法自动回收的,需要手动进行释放操作,此操作需要在finally中进行
  • 4、try_catch_finally可以进行嵌套
public void test2(){
        FileInputStream fis = null;
        try {
            File file = new File("hello.txt");
            fis = new FileInputStream(file);
                
            int data = fis.read();
            while(data != -1){
                System.out.print((char)data);
                data = fis.read();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

体会1:使用try_catch_finally处理编译时异常,使得程序在编译阶段不会报错;但程序在运行时仍然有可能报错;相当于用try_catch_finally将一个编译时可能出现的异常,延迟到了运行时出现

体会2:由于开发中运行时异常比较常见,我们不会编写针对它的异常处理;对于编译时异常,我们才会考虑其异常处理

异常处理2:throws

throws + 异常类型
写在方法声明处,指明当方法执行时,可能抛出的异常类型
一旦该方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后面的异常类型时,就会被抛出。并且后续的代码不会被执行
总的来说,try_catch_finally会确实地将异常给处理掉,而throws只是将异常抛给了方法的调用者,并没有真正处理异常

public class Throws {
    
    public static void main(String[] args) {
        try{
            method2();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    
    public static void method2() throws FileNotFoundException,IOException{
        method();
    }
    
    public static void method() throws FileNotFoundException,IOException{
        File file = new File("hello.txt");
        FileInputStream fis = new FileInputStream(file);
                
        int data = fis.read();
        while(data != -1){
            System.out.print((char)data);
            data = fis.read();
        }
            
        fis.close();

    }
}

手动抛出异常:throw

Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要使用人工创建并抛出

// 手动抛出异常

public class Throw {
    public static void main(String[] args) {
        try{
            Student s = new Student();
            s.getID(-1001);
            System.out.println(s.toString());
        }catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

class Student{
    private int ID;
    
    public void getID(int ID) throws Exception{
        if(ID >= 0)
            this.ID = ID;
        else
//          System.out.println("输入的值非法!");
//          throw new RuntimeException("输入的值非法!");
            throw new Exception("输入的值非法!");
    }

    @Override
    public String toString() {
        return "Student [ID=" + ID + "]";
    }
}

【子类重写的方法】抛出的异常类型不能大于【父类被重写的方法】抛出的异常类型

public class OverrideTest { 
    public static void main(String[] args) {
        OverrideTest test = new OverrideTest();
        test.display(new SubClass());
    }
    
    public void display(SuperClass s){
        try {
            s.method();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class SuperClass{
    public void method() throws IOException{  };
}

class SubClass extends SuperClass{
    public void method() throws FileNotFoundException{  };
}

自定义异常

用户自定义异常类MyException,用于描述数据取值范围错误信息。用户自己的异常类必须继承现有的异常类。

  • 一般地,用户自定义异常类都是RuntimeException的子类。
  • 自定义异常类通常需要编写几个重载的构造器。
  • 自定义异常需要提供serialVersionUID
  • 自定义的异常通过throw抛出。
  • 自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。
public class MyException extends RuntimeException{
    
    static final long serialVersionUID = -317519865L;
    
    public MyException(){
        
    }
    
    public MyException(String msg){
        super(msg);
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容