Java异常

异常

程序在运行过程中, 非常可能遇到异常问题, Exception

  • 异常处理框架

  • 检查性异常: 用户错误或问题引起, 是程序员无法预见的. 例如打开不存在的文件, 这些异常在编译时不能被简单地忽略

  • 运行时异常: 可被程序员避免的异常. 运行时异常可以在编译时被忽略

  • 错误ERROR: 脱离程序员控制的问题.例如栈溢出

java可以把异常当作对象来处理, 并定义一个基类Java.lang.Throwable作为所有异常的超类

Java API中定义了许多异常类, 分为两大类, 错误Error和异常Exception

Error

Error类对象由java虚拟机生成并抛出

当JVM不再有继续执行操作所需的内存资源时,将出现OutOfMemoryError. 这些异常发生时, Java虚拟机一般会选择线程终止

Exception

有一个重要的子类RuntimeException(运行时异常)

  • ArrayIndexOutOfBoundsException(数组下标越界)
  • NullPointerException (空指针异常)
  • ArithmeticException(算数异常)
  • MissingResourceException(丢失资源)
  • ClassNotFoundException(找不到类)

这些异常时不检查异常,通常由程序逻辑引起

Error和Exception的区别: Error通常是灾难性的致命错误, 是程序无法控制和处理的, 当出现时Java虚拟机一般会选择终止线程; Exception通常可以被程序处理, 并在程序中应该尽可能的去处理这些异常

异常处理机制

image-20210224153744312

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){//catch(想要捕获的异常类型) 捕获异常
            System.out.println("程序出现异常,变量b不能为0");
        }finally { //处理善后工作
            System.out.println("finally");
        }
    }
}

finally可以不需要, IO,资源,关闭需要finally

package Demo02;

public class Test {
    public static void main(String[] args) {

        int a = 1;
        int b = 0;

        //要捕获多个异常要从小到大捕获
        try{//try监控区域
            System.out.println(a/b);
        }catch(Error e){//catch 捕获异常
            System.out.println("Error");
        }catch (Exception r){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        }
        finally { //处理善后工作
            System.out.println("finally");
        }
    }
}

选中Ctrl+Alt+T快捷键

public class Test {
    public static void main(String[] args) {

        new Test().test(1,0);
    }

    //假设在方法中,处理不了这些异常.方法上抛出异常
    public void test(int a, int b) throws ArithmeticException{
        if(b==0){ //throw 和 throws不一样
            throw new ArithmeticException();//主动抛出 一个异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}
posted @ 2021-02-25 13:49  SagiriV  阅读(42)  评论(0)    收藏  举报