Java异常处理机制总结

一、常见异常分类

在这里插入图片描述

二、异常处理

2.1异常处理流程

  1. 程序中产生异常后,JVM根据异常的类型实例化异常类的对象;若程序中不存在异常处理操作,则这个实例化的对象的默认处理方式是JVM进行异常信息的输出,而后中断程序。
  2. 存在异常处理,由try语句捕获该异常对象,与程序后面的catch进行匹配,匹配失败则交由JVM处理。
  3. 有无异常都会执行finally中的程序,若无异常,fianlly语句执行完后继续后面的程序语句;若存在没有能够处理的异常对象,finally语句后交给JVM进行异常信息的输出,并且中断程序;

2.2编译时异常处理方式

  1. throws关键字处理:
    当前方法不用处理该异常对象,可以直接将异常对象抛出给他的调用者(上级),由上级处理,若所有调用者都无处理或(最顶级的调用者main函数里都没有处理该异常),则由JVM输出异常信息,程序中断。
  2. try{…}catch{…}finally{…}语句处理
    格式:
    try{
    可能出现异常的代码块,范围越少越好;
    }catch(异常类型 异常对象名){
    异常处理语句;
    }finally{
    需要释放的资源;
    }
    public static void main(String[] args) {
        try {
            Trycat.cout();
        } catch (ArithmeticException ex) {
            ex.printStackTrace();//给出更为详细的异常处理信息;
        } finally {
            System.out.println("此行代码一定会被执行");
        }
    }
    private static void cout() throws ArithmeticException{
        int i =10, j=0;
        int k =i / j;;
    }

处理结果:
在这里插入图片描述

  1. throw 关键字自定义异常
    (1)手动抛出异常
public class Throws {
    public static void main(String[] args) {
        Student stu = new Student();
        try {
            stu.regist(-30);
        }catch (Exception e){
            //e.printStackTrace();
            System.out.println(e.getMessage());//通过Exception的构造方法输出
        }
        System.out.println(stu);
    }
}
class Student{
    private int id;
    public void regist(int id)throws Exception{
        //throw new RuntimeException("您输入了非法数字");//运行时异常可以直接抛出,在运行时候解决异常就可以了,运行时异常可以不处理,报错就行了
        if(id > 0){
            this.id = id;
        }else throw new Exception("您输入了非法数字");//编译时异常必须处理
    }
}

在这里插入图片描述throw小结:throw只能抛出一个异常类的对象

(2)自定义异常:

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

        }
        public MyException(String msg){
            super(msg);
        }
}
public class Throws {
    public static void main(String[] args) {
        Student stu = new Student();
        try {
            stu.regist(-30);
        }catch (Exception e){
            //e.printStackTrace();
            System.out.println(e.getMessage());//通过Exception的构造方法输出
        }
        System.out.println(stu);
    }
}
class Student{
    private int id;
    public void regist(int id)throws MyException{
        if(id > 0){
            this.id = id;
        }else throw new MyException("您输入了非法数字");//编译时异常必须处理
    }
}

在这里插入图片描述

发布了23 篇原创文章 · 获赞 4 · 访问量 616

猜你喜欢

转载自blog.csdn.net/weixin_43331769/article/details/103609688