进阶day05-运行时异常和编译时异常的区别

This commit is contained in:
2026-02-04 13:46:44 +08:00
parent e75e2b22de
commit 1935bd609d

View File

@@ -0,0 +1,34 @@
package com.inmind.exception05;
/*
运行时异常和编译时异常的区别
运行时异常(RunTimeException及其子类):属于非检查型异常(编译器不检查),无需强制处理,可以通过优化代码逻辑,避免异常
编译时异常(Exception及其子类但与RunTimeException无关):属于检查型异常(编译器会检查),在编写阶段可能出现语法问题必须处理。
需要程序员预见并处理可能的错误情况可通过try-catch或throws处理
总结:编写代码时,编译时异常一定要处理,运行时异常可以处理,也可以不处理
在一个方法中异常处理的方式有2种:1.真正的处理try-catch 2.交给调用者处理throws
*/
public class Demo08 {
public static void main(String[] args) {
try {
method2();
} catch (Exception e) {
System.out.println();
} finally {
}
System.out.println("程序结束");
}
public static void method1() throws Exception {
throw new Exception();
}
public static void method2() {
throw new RuntimeException();
}
}