Loading

Java异常处理

异常概述

异常:指的是程序运行过程中,出现的不正常的情况。

异常的根类是java.lang.Throwable,其下有两个子类:java.lang.Errorjava.lang.Exception

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

  • Error(错误):Java虚拟机无法解决的严重问题,如JVM系统内部错误,资源耗尽等情况,一般不编写针对性的代码进行处理。
  • Exception(异常):其他因编程错误或偶然的外在因素导致的一致性问题,可以用针对性的代码进行处理。
    • 编译时异常(checked):通常时由语法错误和环境因素(外部资源)造成的异常。比如输入输出异常 IOException,数据库操作 SQLException。
    • 运行时异常(unchecked):一般由程序逻辑错误引起的,比如NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException、NumberFormatException。

异常的处理方式

Java有两种异常处理方式:

  • try-catch-finally
  • throws + 异常类型

try-catch-finally的方式

try{
    //可能出现的异常
}catch(异常类型1 变量名1){
    //处理异常的方式1
}catch(异常类型2 变量名2){
	//处理异常的方式2
}
...
 finally{
     //一定会执行的代码
 }

示例:

public class ExceptionTest1 {
    @Test
    public void test1() {
        String str = "123";
        str = "abc";
        try {
            int num = Integer.parseInt(str);
            System.out.println(num);
        } catch (NumberFormatException e) {
            System.out.println("出现了数值转换异常");
        } catch (NullPointerException e) {
            System.out.println("出现了空指针异常");
        }
    }
}

说明:

  • finally是可选的。
  • catch中的异常类型如果满足父子类关系,则要求子类一定声明在父类的上面。
  • finally中声明的是一定会执行的代码,即使try和catch中有return语句。
  • 像数据库连接,输入输出流,网络编程Socket等,JVM是不能自动回收的,此时的资源释放需要声明在finally中。
public class FinallyTest1 {
    @Test
    public void testMethod(){
        int num = method();
        System.out.println(num);
    }

    public int method() {
        try {
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            return 2;
        }finally {
            System.out.println("一定会执行的");
        }
    }
}

输入内容如下:

一定会执行的
2

throws的方式

throws+异常类型的方式写在方法的声明处,指明此方法执行时,可能会抛出的异常类型。一旦出现异常类的对象满足throws后异常类型时,就会被抛出。

public class ExceptionTest2 {
    public void method2() throws FileNotFoundException, IOException {
        File file = new File("/hello.txt");
        FileInputStream fis = new FileInputStream(file);
        int data = fis.read();
        while (data != -1) {
            System.out.println((char) data);
            data = fis.read();
        }
        fis.close();
    }
}

手动抛出异常

使用throw关键字抛出一个异常。

public class StudentTest {
    public static void main(String[] args) {
        Student s = new Student();
        s.register(-1001);
        System.out.println(s);
    }
}

class Student{
    private int id;
    public void register(int id){
        if (id>0){
            this.id = id;
        }else {
            //手动抛出异常对象
            throw new RuntimeException("您输入的数据非法!");
        }
    }
}

自定义异常

1.自定义异常需要继承于现有的异常结构,RuntimeException、Exception。

2.提供全局常量:serialVersionUID

3.提供重载的构造器

public class MyException extends RuntimeException {
    static final long serialVersionUID = -703423782341234L;
    public MyException() {

    }
    public MyException(String msg) {
        super(msg);
    }
}
posted @ 2021-10-27 14:06  charlatte  阅读(78)  评论(0编辑  收藏  举报