JavaSE异常处理

在Java中,将程序执行中发生的不正常的情况称之为“异常 ”,(语法错误与逻辑错误不是异常)

Java程序在执行过程中发生的异常可以分为两类:

  • Error:Java虚拟机无法解决的问题,如
    • StackOverflowError(栈溢出)
    • OOM(内存溢出)
  • Exception:由于编程错误或者偶然的外在因素导致的一般性问题,如
    • 空指针
    • 读取不存在的文件
    • 数组越界
    • 网络问题

一、Java异常体系结构

  • 编译型异常:checked
  • 运行时异常:unchecked

二、常见异常

运行时异常

2.1 NullPointerException

@Test
public void test1() {
    String a = null;
    System.out.println(a.charAt(0));
}

2.2 ArrayIndexOutBoundsException

@Test
public void test2() {
    int[] arr = new int[10];
    System.out.println(arr[10]);
}

2.3 ClassCastException

@Test
public void test3() {
    Object date = new Date();
    String str = (String) date;
}

2.4 NumberFormatException

@Test
public void test4() {
    String str = "123";
    str = "ABC";
    int i = Integer.parseInt(str);
}

2.5 InputMismatchException

@Test
public void test5() {
    Scanner scanner = new Scanner(System.in);
    scanner.nextInt();
}

2.6 ArithmeticException

@Test
public void test6() {
    int a = 0;
    int b = 2;
    System.out.println(b / a);
}

编译时异常

@Test
public void test7() {
    File file = new File("hello.txt");
    FileInputStream fileInputStream = new FileInputStream(file);

    int data = fileInputStream.read();
    while (data != -1) {
        System.out.println((char)data);
        data = fileInputStream.read();
    }
    fileInputStream.close();
}

三、异常处理机制

Java对于异常的处理:抓抛模型

  • 抛:程序执行中,一旦出现异常,就在异常代码处生成一个对应异常类的对象。并将对象抛出,一旦抛出对象,其后面的代码就不再执行
  • 抓:异常的处理方式:1.try-catch-finally 2.throws

3.1 try-catch-finally

  • finally可选,其声明的是一定会执行的代码,像JVM不能自动回收,手动资源释放需要声明在finally中
  • 使用try将可能出现的异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中进行匹配
  • 一旦try的异常对象匹配到某一个catch时,就进入catch中进行异常的处理,处理完成就退出
  • catch中异常类型若没有子父类关系,则无序,若有关系,则子类必须在父类前面,否则会报错
  • 常用的异常对象处理方式: 1. String getMessage() 2. printStackTrace()
@Test
public void test1() {
    String str = "123";
    str = "abc";

    try{
        int num = Integer.parseInt(str);
    }catch (NullPointerException e) {
        System.out.println("出现空指针异常");
    }catch (NumberFormatException e) {
        System.out.println("出现数值转换异常");
    }catch (Exception e) {
        System.out.println("出现异常!");
    }
    ...
        
	finally {
        //一定会执行的代码
    }
}

总结:使用 try-catch-finally处理编译时异常,使得程序在编译时不再报错,但是运行时仍然可能报错

3.2 throws

  • “ throws + 异常类型 ” 写在方法的声明处,指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出

四、自定义异常类

在开发中根据自己业务的异常情况来定义异常类

  • 自定义一个编译期异常: 自定义类 并继承于 java.lang.Exception

  • 自定义一个运行时期的异常类:自定义类 并继承于 java.lang.RuntimeException

猜你喜欢

转载自www.cnblogs.com/yfyyy/p/12735947.html
今日推荐