异常机制(Exception)

异常机制(Exception)

什么是异常

  • 异常程序运行中出现的意外情况,比如找不到文件、网络连接失败等
  • 异常影响程序的执行流程

异常分类

  • 检查性异常:最具代表性的异常是用户错误或问题引起的一场,这是程序员无法遇见的。
  • 运行时异常:运行时异常是可能被程序员避免的。
  • 错误(Error):错误不是异常

异常体系结构

  • Java可以把异常当作一个对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类。
  • 在Java API中已经定义了许多异常类,这些异常分为两大类,错误(Error)和异常(Exception)

Error

  • Error类对象由Java虚拟机生成并抛出,大多数错误代码编写者所执行操作无关
  • Java虚拟机运行错误,当JVM不再有继续中操作所需的内存资源时,将出现OutOfMenoryError。这些异常发生时,JVM一般会选择线程终止

Exception

  • 在Exception分支中有一个重要的子类RuntimeException(运行时异常)
    • ArrayIndexoutOfBoundsException(数组下标越界)
    • NullPointerException(空指针异常)
    • ArithmeticExpection(算数异常)
    • MissingResourceException(资源丢失)
    • ClassNotFoundExpection(找不到类)
  • 二者区别:Error无法控制,JVM通常会终止异常,Exception通常情况下被程序处理

Java异常处理机制

抛出异常

捕获异常

异常处理关键字

  • try
  • catch
  • finally
int a=1;
int b=0;
try { //监控区域
    System.out.println(a/b);
}catch (ArithmeticException e){
    System.out.println("程序出现异常,我在这里捕获了!");
}finally {
    System.out.println("fianlly:我负责处理善后工作,无论出不出异常我都会走");
}
  • throw (抛出异常)
  • throws
public static void main(String[] args) {
    try { //监控区域
        new Student().test(1,0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//方法上抛出异常,假设在这个地方处理不了异常 在方法上用throws
public  void test (int a ,int b) throws Exception{
        if (b == 0) {
            //throw 方法内部抛出异常
            throw new ArithmeticException();
        }
}

自定义异常

  • 使用Java内置异常类可以描述在编程时出现的大部分异常情况.除此之外,用户还可以自定义异常.瀛湖自定义异常类,只需要继承Exception即可
public class Exception extends java.lang.Exception {
    //传递数字>10
    private int detial;

    public Exception(int detial) {
        this.detial = detial;
    }

    @Override
    public String toString() { //异常的打印信息
        return "Exception{" +
                "detial=" + detial +
                '}';
    }
}

public class Test {
    //可能会存在异常的方法
    static void test( int a) throws Exception {
        System.out.println("传递的参数为:"+a);
        if (a >10) {
            throw new Exception(a);
        }else {
            System.out.println("输入数字没有大于10");
        }
    }

    public static void main(String[] args) {
        try {
            test(12);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
----------------------------------
传递的参数为:12
Exception{detial=12}
	at Scanner.OOp.Exception.Test.test(Test.java:8)
	at Scanner.OOp.Exception.Test.main(Test.java:16)

posted on 2021-07-15 20:35  苏必胜666  阅读(0)  评论(0编辑  收藏  举报