Java異常框架設計一

          Posted on 2006-03-02 20:50 killvin 閱讀(646) 評論(1)  編輯  收藏 所屬分類: java

          引言

           記得當初參與某公司的ERP項目中,接觸過異常框架這個概念,可是似乎并沒有感覺到當時技術經理提出這個概念的意義,而且他也對這個概念似乎很"保守",雖然按照他的思路去執行,但沒有理解的概念再實施起來的時候總是覺得很"別扭",而如今面對自己要設計咚咚了,不得不重新審視異常這個概念,JAVA異常的介紹文章在網絡上非常的少,而對于如何構件J2EE的異常處理框架更顯的稀少,于是就促使自己寫下了這樣的文章。

           本文只是自己的一些愚見,希望和大家相互學習。Email:Killvin@hotmail.com

          概念

          什么是異常?

          異常(exception)應該是異常事件(exceptional event)的縮寫。
          異常定義:異常是一個在程序執行期間發生的事件,它中斷正在執行的程序的正常的指令流。
          當在一個方法中發生錯誤的時候,這個方法創建一個對象,并且把它傳遞給運行時系統。這個對象被叫做異常對象,它包含了有關錯誤的信息,這些信息包括錯誤的類型和在程序發生錯誤時的狀態。創建一個錯誤對象并把它傳遞給運行時系統被叫做拋出異常。
          一個方法拋出異常后,運行時系統就會試著查找一些方法來處理它。這些處理異常的可能的方法的集合是被整理在一起的方法列表,這些方法能夠被發生錯誤的方法調用。這個方法列表被叫做堆棧調用(call stack)

          運行時系統搜尋包含能夠處理異常的代碼塊的方法所請求的堆棧。這個代碼塊叫做異常處理器,搜尋首先從發生的方法開始,然后依次按著調用方法的倒序檢索調用堆棧。當找到一個相應的處理器時,運行時系統就把異常傳遞給這個處理器。一個異常處理器要適當地考濾拋出的異常對象的類型和異常處理器所處理的異常的類型是否匹配。異常被捕獲以后,異常處理器關閉。如果運行時系統搜尋了這個方法的所有的調用堆棧,而沒有找到相應的異常處理器。

           

          怎么設計異常框架

          任何的異常都是Throwable類(為何不是接口??),并且在它之下包含兩個字類Error / Exception,而Error僅在當在Java虛擬機中發生動態連接失敗或其它的定位失敗的時候,Java虛擬機拋出一個Error對象。典型的簡易程序不捕獲或拋出Errors對象,你可能永遠不會遇到需要實例化Error的應用,那就讓我們關心一下Exception

          Exception中比較重要的就是RuntimeException-運行時異常(當然這個名字是存在爭議的,因為任何的異常都只會發生在運行時),為什么說這個類時很重要的呢?因為它直接關系到你的異常框架的設計,仔細看RuntimeException

          A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

          -可能在執行方法期間拋出但未被捕獲的 RuntimeException 的任何子類都無需在 throws 子句中進行聲明。

          也就是說你的應用應該不去“關心”(說不關心是不服責任的,但只是你不應該試圖實例化它的字類)RuntimeException,就如同你不應該關心Error的產生與處理一樣!RuntimeException描述的是程序的錯誤引起來的,因該由程序負擔這個責任!(<B>從責任這個角度看Error屬于JVM需要負擔的責任;RuntimeException是程序應該負擔的責任;checked exception 是具體應用負擔的責任</B>)

          那就有人會問,那我該關心什么!答案就是除了Error與RuntimeException,其他剩下的異常都是你需要關心的,而這些異常類統稱為Checked Exception,至于Error與RuntimeException則被統稱為Unchecked Exception.


          異常的概念就這些了,即使你在網絡上搜索也就不過如此,是不是感覺到有點清晰又有點模糊?那么怎么該如何在這樣單薄而模糊的概念下設計J2EE的異常框架呢?


          解決方案:J2EE異常框架

          我們拿一個模擬的例子來說明異常框架的設計過程,比如我們要對外提供doBusiness()這個業務方法

          public void doBusiness() throws xxxBusinessException

          當客戶端調用這樣的方法的時候應該這樣處理異常(包括處理RuntimeException , checked exception)
          <B>記住,無論如何我們都不希望或者確切的說是不應該將RuntimeException這樣的異常暴露給客戶的,因為他們沒有解決這個問題的責任!</B>
          我們暫時將Struts中的某個Action看作時客戶端,其中doExecute(....)要調用doBusiness()這個方法

          public void doAction(......)
          {
           try
           {

            xxx.doBusiness();
           }
           catch(Exception e)
           {
             if(e instanceof RuntimeException) 
             {
              // catch runtime exception
              // 你可以在這里將捕獲到的RuntimeException
              // 將異常通知給某個負責此程序的程序員,讓他知道他
              // 自己犯了多么低級的錯誤!


             }else
             {
              //checked exception such as xxxBusinessException
              //將這樣的異常暴露給客戶顯示    

             }

           }
          }

          我們可以這樣設計xxxBusinessException

          public class xxxBusinessException extends ApplicationException
          {
              public xxxBusinessException(String s){
                  super(s);

          };

          import java.io.PrintStream;
          import java.io.PrintWriter;
          public class ApplicationException extends Exception {
                 /** A wrapped Throwable */
                 protected Throwable cause;
                 public ApplicationException() {
                     super("Error occurred in application.");
                 }
                 public ApplicationException(String message)  {
                     super(message);
                 }
                 public ApplicationException(String message, Throwable cause)  {
                     super(message);
                     this.cause = cause;
                 }
                 // Created to match the JDK 1.4 Throwable method.
                 public Throwable initCause(Throwable cause)  {
                     this.cause = cause;
                     return cause;
                 }
                 public String getMessage() {
                     // Get this exception's message.
                     String msg = super.getMessage();
                     Throwable parent = this;
                     Throwable child;
                     // Look for nested exceptions.
                     while((child = getNestedException(parent)) != null) {
                         // Get the child's message.
                         String msg2 = child.getMessage();
                         // If we found a message for the child exception,
                         // we append it.
                         if (msg2 != null) {
                             if (msg != null) {
                                 msg += ": " + msg2;
                             } else {
                                 msg = msg2;
                             }
                         }
                         // Any nested ApplicationException will append its own
                         // children, so we need to break out of here.
                         if (child instanceof ApplicationException) {
                             break;
                         }
                         parent = child;
                     }
                     // Return the completed message.
                     return msg;
                 }
                 public void printStackTrace() {
                     // Print the stack trace for this exception.
                     super.printStackTrace();
                     Throwable parent = this;
                     Throwable child;
                     // Print the stack trace for each nested exception.
                     while((child = getNestedException(parent)) != null) {
                         if (child != null) {
                             System.err.print("Caused by: ");
                             child.printStackTrace();
                             if (child instanceof ApplicationException) {
                                 break;
                             }
                             parent = child;
                         }
                     }
                 }
                 public void printStackTrace(PrintStream s) {
                     // Print the stack trace for this exception.
                     super.printStackTrace(s);
                     Throwable parent = this;
                     Throwable child;
                     // Print the stack trace for each nested exception.
                     while((child = getNestedException(parent)) != null) {
                         if (child != null) {
                             s.print("Caused by: ");
                             child.printStackTrace(s);
                             if (child instanceof ApplicationException) {
                                 break;
                             }
                             parent = child;
                         }
                     }
                 }
                 public void printStackTrace(PrintWriter w) {
                     // Print the stack trace for this exception.
                     super.printStackTrace(w);
                     Throwable parent = this;
                     Throwable child;
                     // Print the stack trace for each nested exception.
                     while((child = getNestedException(parent)) != null) {
                         if (child != null) {
                             w.print("Caused by: ");
                             child.printStackTrace(w);
                             if (child instanceof ApplicationException) {
                                 break;
                             }
                             parent = child;
                         }
                     }
                 }
                 public Throwable getCause()  {
                     return cause;
                 }
          }

          而"聰明"的讀者肯定要問我那doBusiness()這個業務方法該如何包裝異常呢?

           public void doBusiness() throw xxxBusinessException
           {
             try
             {
               execute1(); // if it throw exception1

               exexute2(); // if it throw exception 2

               .... .....

             }
             catch (exception1 e1)
             {
              throw new xxxBusinessException(e1);
             }
             catch(exception2 e2)
             {
              throw new xxxBusinessException(e2);
             }
             ........
           }

           也可以這樣

           public void doBusiness() throw xxxBusinessException
           {
             try
             {
               execute1(); // if it throw exception1

               exexute2(); // if it throw exception 2

               .... .....

             }
             catch (Exception e)
             {
              // 注意很多應用在這里根本不判斷異常的類型而一股腦的采用
              // throw new xxxBusinessException(e);
              // 而這樣帶來的問題就是xxxBusinessException"吞掉了"RuntimeException
              // 從而將checked excption 與unchecked exception混在了一起!

              // 其實xxxBusinessException屬于checked excpetion ,它根本不應該也不能夠理睬RuntimeException
              if(! e instanceof RuntimeException) throw new xxxBusinessException(e);
             }
           }


          總結
           1。JAVA的異常分為兩類: checked exception & unchecked excpetion
           2。應用開發中產生的異常都應該集成自Exception 但都屬于checked excpetion類型
           3。應用中的每一層在包裝并傳遞異常的時候要過濾掉RuntimeException!
           4。從責任這個角度看Error屬于JVM需要負擔的責任;RuntimeException是程序應該負擔的責任;checked exception 是具體應用負擔的責任
           5。無論如何我們都不希望或者確切的說是不應該將RuntimeException這樣的異常暴露給客戶的,因為他們沒有解決這個問題的責任!

          主站蜘蛛池模板: 新平| 英超| 泽普县| 彝良县| 南皮县| 合山市| 纳雍县| 海淀区| 策勒县| 会泽县| 莲花县| 承德县| 博野县| 壤塘县| 岢岚县| 华阴市| 乌苏市| 安庆市| 施秉县| 台安县| 孟津县| 子洲县| 鱼台县| 太白县| 临西县| 双牌县| 巴青县| 出国| 繁峙县| 宝应县| 临沂市| 九江县| 连城县| 上杭县| 临江市| 徐水县| 夏河县| 新干县| 依安县| 中卫市| 信宜市|