異常在Dos中顯示的一些問題……

1Exception(String message): Constructs a new exception with the specified detail message

//此爲異常類Exception的一個構造方法。該方法用於自定義異常類時使用。

自定義一個異常類:(舉例)

public class MyException extends Exception {

     private int id;

     MyException(String s,int id) {

       super(s);//這個地方就是用了上述提到的Exception(String message): 構造方法。

       this.id = id;

     }

}

2:public class Test {

      public void regist(int num) throws MyException {

             if(num < 0) {

                    throw new MyException("登記人數爲負值!",3);

             }

             System.out.println("登記人數爲:" + num);

      }

      public void manager() {

             try {

                    regist(-1);

             } catch(MyException e) {

                    System.out.println("登記失敗,出錯類型碼爲:"+ e.getId());

                    e.printStackTrace();

             }

             System.out.println("操作結束!");

      }

      public static void main(String[] args) {

                    Test t = new Test();                                              

                    t.manager();

      }

}

//Dos下的顯示如圖:


 

MyException:登記人數爲負值!是e.printStackTrace();造成的。輸出的內容爲throw new MyException("登記人數爲負值!",3);注意:printStackTrace();爲把堆棧內的所有信息都打印出來。

 

public void manager() {

             try {

                    regist(-1);

             } catch(MyException e) {

                    e.printStackTrace();

                    System.out.println("登記失敗,出錯類型碼爲:"+ e.getId());

 

             }

             System.out.println("操作結束!");

      }

注意:如果把粗體的部分像上述代碼顛倒放置,則Dos下異常顯示順序爲:

3:對於try catch finally執行的一些理解:

finally和沒有finally的區別。

如果在try語句塊內存在return語句,finally子句中的代碼會在返回前執行。

如果catch語句中有return語句,則如果不加finally,則不會被執行。如:

public class TestFinal {

      public static void main(String[] args) {

             TestFinal me = new TestFinal();

             try {

                    me.m();

                    

             } catch(Exception e) {

                           e.printStackTrace();

                           return;

                }

                finally {

                           System.out.println("嘿嘿……");

                    }

      }

      public void m() throws Exception {

             throw new Exception("出錯啦,呵呵……");

      }

}//如果加finally,則會執行System.out.println("嘿嘿……");

如果不加finally,System.out.println("嘿嘿……");不會被執行。總之如果異常處理之後還有別的語句想要被執行,則最好是要加上finally語句。

 

      

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發佈了25 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章