throw 与 throws的应用

throws---------->把异常交给调用处。

可以结合throw来同时使用。

throws 用在方法声明处,表示本方法不处理异常。可以结合throw使用

throw 表示在方法中手工抛出一个异常。

 

 1 class Math {
 2     public int div(int i, int j) throws Exception {        // 交给调用处
 3         System.out.println("********计算开始********");
 4         int temp = 0;
 5         try {
 6             temp = i / j;
 7         } 
 8         catch (Exception e) {
 9             throw e;                                     // 交给调用处
10         } 
11         finally {                                        // 必须执行
12             System.out.println("*********** END ********");
13         }
14         return temp;
15     }
16 }
17 
18 public class ThrowsDemo1 {
19     public static void main(String args[]) {
20         Math m = new Math();            // 实例化Math对象
21         
22         try {
23             System.out.println("除法操作: " + m.div(10,0));
24         }
25         catch (Exception e) {                            // 进行异常捕获
26             System.out.println("异常产生: " + e);
27         }
28     }
29 }

 

当内部要finally时,则用throw来交给调用处出来。

posted @ 2014-09-27 22:58  daishuguang  阅读(328)  评论(0编辑  收藏  举报