0%

RuntimeException

文章字数:97,阅读全文大约需要1分钟

RuntimeException 和 Exception

相同

  1. RuntimeException 继承与 Exception
  2. RuntimeExceptionException都能被try...catch

不同

  1. 如果程序抛出Exception,编译器会要求代码中处理,即try...catchthrows
  2. RuntimeException可以不在代码中处理,运行时遇到则会抛出。例如空指针异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
runtimeException(); // 可以不处理,运行时会直接抛出异常
try {
exception(); // 必须try catch
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

private static void runtimeException() {
throw new RuntimeException("runtime exception");
}

private static void exception() throws Exception {
throw new Exception("exception");
}