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()加下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