Exception与Error

suaxi
2020-11-19 / 0 评论 / 93 阅读 / 正在检测是否收录...
异常

什么是异常(Exception)?

指程序运行过程中出现的不期而至的各种状况,例如:找不到文件,网络连接失败,非法参数等

1、检查性异常,用户错误或问题引起的异常

2、运行时异常,与检查性异常相反,运行时异常可以在编译时被忽略

3、错误(Error),错误不是异常,而是脱离程序员控制的问题

在Exception分支中有一个重要的子类RuntimeException(运行时异常)

  • ArrayIndexOutOfBoundsException 数组下标越界
  • NullPointerException 空指针异常
  • ArithException 算数异常
  • MissingResourceException 丢失资源
  • ClassNotFoundException 找不到类等异常,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理

这些异常一般是由程序逻辑错误引起的,应尽量避免

package com.exception;

/**
 * @Author suaxi
 * @Date 2020/11/19 16:16
 */
public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try { // 监控区域
            System.out.println(a/b);
        }catch (Error e){ //catch(想要捕获的异常类型)
            System.out.println("Error");
            e.printStackTrace(); //打印错误的栈信息
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        }finally {
            System.out.println("finally");
        }
    }
    public void a(){
        b();
    }

    public void b(){
        a();
    }
}
package com.exception;

/**
 * @Author suaxi
 * @Date 2020/11/19 16:36
 */
public class Test01 {
    public static void main(String[] args) {
        try {
            new Test01().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }

    public void test(int a,int b) throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException(); //主动抛出异常
        }
    }
}
Error

Error类对象由JAVA虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关

Java虚拟机运行错误(Virtual MachineError),当JVM不再有继续执行所需的内存资源时,将出现OutOfMemoryError,这些错误出现时,JVM一般会选则线程终止

还有发生在虚拟机试图执行应用时,如类定义错误(NoClassDefFoundError)、链接错误(LinkageError)。这些错误是不可检查的,因为它们在应用程序的控制和处理能力之外,而且绝大多数是程序运行时不允许出现的状况。

Exception与Error的区别:

Error通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时,JVM一般会选择终止线程;Exception通常情况下是可以被程序处理的,在程序中应尽可能的去处理这些异常。

0

评论 (0)

取消