Exception是检查型异常,在程序中必须使用try...catch进行处理;
RuntimeException是非检查型异常,例如NumberFormatException,可以不使用try...catch进行处理,但是如果产生异常,则异常将由JVM进行处理;
RuntimeException用法:
代码语言:javascript复制package m01d01;
public class Exception01 {
public static void testRuntimeException() throws RuntimeException{
throw new RuntimeException("运行时异常");
}
public static void testException() throws Exception{
throw new Exception("编译时异常");
}
public static void main(String[] args) {
testRuntimeException();
}
}
可以看见,运行时异常可以不用 try...catch进行处理,仍然能运行成功;
结果为:
但是Exception必须要捕获,否则编译就会报错:
使用try...catch进行处理后:
代码语言:javascript复制package m01d01;
public class Exception01 {
public static void testRuntimeException() throws RuntimeException{
throw new RuntimeException("运行时异常");
}
public static void testException() throws Exception{
throw new Exception("编译时异常");
}
public static void main(String[] args) {
try {
testException();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testRuntimeException();
}
}
输出结果: