关于异常处理

异常的一般在的处理是:

C#:在方法中用try.catch.finally 语句块捕获异常  在catch 中抛出(throw)异常  

然后在方法的调用处应try  catch 直接输出异常信息。

java:在方法名称后加throws Exception:交给使用者处理  并在方法中捕获并抛出异常。在方法调用中直接用try  catch 输出异常。

 1 class A
 2 {
 3     public int div(int a,int b)throws Exception{//把异常交给调用者处理
 4         int temp=0;
 5         try
 6         {
 7             temp=a/b;
 8         }
 9         catch (Exception ex)
10         {
11             throw ex;//抛出异常
12         }
13         finally
14         {
15             
16             //释放资源等操作代码
17         }
18         return temp;
19     }
20 
21 }
22  class ExceptionTest
23 {
24      
25     public static void main(String args[]){
26         A a=new A();
27         try
28         {
29             a.div(10,0);    
30         }
31         catch (Exception ex)
32         {
33             System.out.println("异常信息为:"+ex);//输出异常信息
34         }
35         
36     }
37 }

  注: 应该声明方法抛出异常还是在方法中捕获异常?原则:捕捉并处理哪些知道如何处理的异常,而传递哪些不知道如何处理的异常。

 

细节处理:

 可以多重catch。 前面可以放Exception子类异常  注意Exception异常需要放在最后面。

posted on 2012-10-12 10:30  百零八1900  阅读(119)  评论(0)    收藏  举报

导航