Error 和 Exception
Error 和 Exception
程序中的错误
问题代码:
package com.exception;
public class Demo01 {
public static void main(String[] args) {
new Demo01().a();
}
public void a() {
b();
}
public void b() {
a();
}
}
运行报错:

java异常
- 检查性异常:用户错误或问题引起的异常,程序无法预见
- 运行时异常:与检查性异常相反,可以在编译时被忽略
- 错误ERROR:属于脱离程序员控制的问题,比如栈溢出
Error
- Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关
- Java虚拟机运行错误(VirtualMachineError),当Java虚拟机不再有继续执行程序操作所需的内存资源时,将出现OutOfMemoryError。这些异常发生时,Java虚拟机一般会选择线程终止
- 还有发生在虚拟机试图执行应用时,如类定义错误(NoClassDefFoundError)、链接错误(LinkageError)。这些错误是不可查的,因为他们在应用程序的控制和处理能力之外
Exception
- 重要子类Runtime Exception
- 一般是由程序逻辑错误引起的,应该尽量避免
package com.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1, 0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}
//假设这个方法中处理不了这个异常,可以在方法上抛出这个异常
public void test(int a, int b) throws ArithmeticException {
if (b == 0) { //throw和throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
}
}
/**
* int a = 1;
* int b = 0;
* <p>
* <p>
* //捕获异常,要按范围从小到大依次捕获
* //快捷键 CTRL + alt + T
* try {//监控区域
* <p>
* if (b == 0) {
* throw new ArithmeticException();//主动抛出异常
* }
* System.out.println(a / b);
* <p>
* } catch (Error e) {//捕获异常 catch(要捕获的异常类型)
* System.out.println("Error");
* } catch (Exception e) {
* System.out.println("Exception");
* } catch (Throwable e) {
* System.out.println("Throwable");
* } finally {//处理善后工作
* System.out.println("finally");
* }
*/

浙公网安备 33010602011771号