Java异常处理-Exception 和 RuntimeException 区别
Exception是检查型异常,在程序中必须使用try...catch进行处理;
RuntimeException是非检查型异常,例如NumberFormatException,可以不使用try...catch进行处理,
但是如果产生异常,则异常将由JVM进行处理;
RuntimeException最好也用try...catch捕获;
上代码:
package com.java1234.chap04.sec04; public class Demo1 { /** * 运行时异常,编译时不检查,可以不使用try...catch捕获 * @throws RuntimeException */ public static void testRuntimeException()throws RuntimeException{ throw new RuntimeException("运行时异常"); } /** * Exception异常,编译时会检查,必须使用try...catch捕获 * @throws Exception */ public static void testException()throws Exception{ throw new Exception("Exception异常"); } public static void main(String[] args) { testException(); testRuntimeException(); } }
我们会发现 testException()报错了 编译不通过 但是testRuntimeException()就编译通过了。
我们对testException()加下try...catch即可;
package com.java1234.chap04.sec04; public class Demo1 { /** * 运行时异常,编译时不检查,可以不使用try...catch捕获 * @throws RuntimeException */ public static void testRuntimeException()throws RuntimeException{ throw new RuntimeException("运行时异常"); } /** * Exception异常,编译时会检查,必须使用try...catch捕获 * @throws Exception */ public static void testException()throws Exception{ throw new Exception("Exception异常"); } public static void main(String[] args) { try { testException(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } testRuntimeException(); } }
运行输出:
java.lang.Exception: Exception异常
at com.java1234.chap04.sec04.Demo1.testException(Demo1.java:18)
at com.java1234.chap04.sec04.Demo1.main(Demo1.java:23)
Exception in thread "main" java.lang.RuntimeException: 运行时异常
at com.java1234.chap04.sec04.Demo1.testRuntimeException(Demo1.java:10)
at com.java1234.chap04.sec04.Demo1.main(Demo1.java:29)
当然,我们一般建议 testRuntimeException()也加下try...catch;