Runtime 异常和Checked异常

Java中的异常被分为两类,Checked异常和Runtime异常,即编译时异常和运行时异常。

所有RuntimeException类及其子类的实例被称为Runtime异常.

对于Checked异常的处理方式有两种:

  1. 当前方法明确知道如何处理该异常,程序应该使用try....catch 块来捕获该异常,然后在对应的catch块中修补该异常.
  2. 当前方法不知道如何处理该异常,应该在定义该方法时声明抛出该异常.

Runtime异常比较灵活,它无须显示的声明抛出.如果程序需要捕获Runtime异常,也可以使用try....catch 块来捕获Runtime异常.

下面的代码是一个很好的例子:

  1. public class TestThrow {  
  2.   
  3.     public static void main(String[] args) {  
  4.          
  5.        try {  
  6.            //调用throws声明的方法,必须显示捕获该异常  
  7.            //否则必须在main方法中再次的声明抛出  
  8.            throwChecked(3);  
  9.     } catch (Exception e) {  
  10.         System.out.println(e.getMessage());  
  11.       }  
  12.         //调用捕获Runtime异常的方法,可以显示的捕获该异常,也可以不理会该异常  
  13.         throwRuntime(4);  
  14.     }  
  15.       
  16.     public static void throwChecked(int a) throws Exception{  
  17.           if(a>0){  
  18.               //自行抛出Exception异常  
  19.               //该代码必须处于try块里,或者处于带throws声明的方法中  
  20.               throw new Exception("a的值大于0,不符合要求");  
  21.           }  
  22.     }  
  23.       
  24.     public static void throwRuntime(int a){  
  25.         if(a>0){  
  26.             //自行抛出RuntimeException异常,既可以显示捕获该异常  
  27.             //也可以完全不理会该异常,把该异常交给方法调用者处理  
  28.             throw new RuntimeException("a的值大于零,不符合要求");  
  29.         }  
  30.           
  31.     }  
  32.   
  33. }  

可以看到程序代码中:Runtime异常没有使用throws声明抛出,也没有使用try...catch块来捕获处理。Checked异常就必须声明抛出或者捕获。运行程序代码时,会出现异常.

posted @ 2015-06-16 09:46  Q_Quan  阅读(172)  评论(0)    收藏  举报