Java異常框架設計

什麼是異常?

異常(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這樣的異常暴露給客戶的,因爲他們沒有解決這個問題的責任!

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