s-day05-运行时异常和编译时异常的区别
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package com.inmind.exception_trycatch02;
|
||||
/*
|
||||
运行时异常和编译时异常的区别
|
||||
运行时异常(RuntimeException):属于非检查型异常,无需强制处理,可以通过优化代码逻辑,避免异常。
|
||||
编译时异常(非RuntimeException):属于检查型异常,在编写阶段,可能出现语法问题必须处理,需要程序员预见并处理可能的异常情况,可以通过try-catch或throws处理
|
||||
|
||||
总结:编写代码时,编译时异常必须处理,而运行时异常,可以选择性地处理
|
||||
|
||||
一个方法中的异常可以有2种处理方式:
|
||||
1.throws 声明出去,交给别人处理
|
||||
2.try-catch 自己处理
|
||||
在main方法顶层,真正能处理掉异常的只有try-catch
|
||||
*/
|
||||
public class Demo08 {
|
||||
public static void main(String[] args) {
|
||||
method1();
|
||||
|
||||
try {
|
||||
method2();
|
||||
} catch (Exception e) {
|
||||
System.out.println("处理了编译时异常");
|
||||
}
|
||||
System.out.println("程序结束");
|
||||
}
|
||||
|
||||
private static void method2() throws Exception{
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
private static void method1() {
|
||||
try {
|
||||
throw new RuntimeException("抛出一个运行时异常");
|
||||
} catch (RuntimeException e) {
|
||||
System.out.println("处理了运行时异常");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user