Java异常机制

异常机制

一、Error 和 Exception

1.什么是异常

  • 异常指程序运行过程中出现的不期而至的各种状况,例如:文件找不到、网络连接失败、非法参数等
  • 异常发生在程序运行期间,它影响了正常的程序执行流程

2.分类

  • 检查性异常 : 用户错误或问题引起的异常,这是程序员无法预见的。例如打开一个不存在的文件,一个异常就产生了。这些异常在编译时不能被简单忽略。
  • 运行时异常: 与检查性异常相反,运行时异常可以在编译时被简单忽略。
  • 错误: 错误不是异常,而是脱离程序员控制的问题。例如当栈溢出时,一个错误就发生了。它们在编译也检查不到的。

3.异常体系结构

  • Java把异常当做对象来处理,并定义一个基类java.lang.Throwable 作为所有异常的超类
  • 在Java API 中已经定义了许多异常类,这些异常类分为两大类,错误Error 和 异常Exception
  • Error类对象有Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关

在这里插入图片描述

二、异常处理机制

  • 抛出异常
  • 捕获异常
  • 异常处理5个关键字:try , catch , finally , throw , throws
 try { 
       //try:监控区域  
        }catch ( 想要捕获的异常类型){
         //如果监控区域出现了ArithmeticException这个异常就执行这个
        }

1.捕获异常(ArithmeticException)

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try { //try:监控区域
            System.out.println(a/b);
        }catch (ArithmeticException e){
            System.out.println("程序出现异常,b不能为0" );//如果监控区域出现了ArithmeticException这个异常就执行这个
        }finally {
            System.out.println("finally");
        }
    }
}

运行结果
请添加图片描述

2.捕获异常(Throwable)

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try {
               new Test().a();
        }catch (Error e){
            System.out.println("程序出现异常 " );
        }
        finally {
            System.out.println("finally");
        }
    }

    public void a(){
        b();
    }
    public void b(){
        a();
    }
}

3.捕获多个异常(从小到大捕获)

        try {
            
        }catch (Error e){
            System.out.println("程序出现异常 Error" );
        }catch (Exception e){
            System.out.println("程序出现异常 Exception" );
        }catch (Throwable e){
            System.out.println("程序出现异常 Throwable" );
        }
        finally {
            System.out.println("finally");
        }

4.对一行代码自动 tyr catch

Ctrl + Alt + T

在这里插入图片描述

try {
           System.out.println(a/b);
       } catch (Exception e) {
           e.printStackTrace(); //打印错误的栈信息
       } finally {
       }

5.主动抛出异常(throw)

在这里插入图片描述

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try {
            if (b == 0){
                throw new ArithmeticException(); //主动抛出异常
            }
            System.out.println(a/b);
        }catch (Throwable e){
            System.out.println("程序出现异常 Throwable" );
        }
        finally {
            System.out.println("finally");
        }
    }

6. 主动抛出异常(throws)

在这里插入图片描述

posted @ 2021-07-30 02:14  小芦荟同学  阅读(34)  评论(0编辑  收藏  举报