Java異??蚣茉O計
作者:E動(dòng)中國 日期:2006-04-30
概念
什么是異常?
異常(exception)應該是異常事件(exceptional event)的縮寫(xiě)。
異常定義:異常是一個(gè)在程序執行期間發(fā)生的事件,它中斷正在執行的程序的正常的指令流。
當在一個(gè)方法中發(fā)生錯誤的時(shí)候,這個(gè)方法創(chuàng )建一個(gè)對象,并且把它傳遞給運行時(shí)系統。這個(gè)對象被叫做異常對象,它包含了有關(guān)錯誤的信息,這些信息包括錯誤的類(lèi)型和在程序發(fā)生錯誤時(shí)的狀態(tài)。創(chuàng )建一個(gè)錯誤對象并把它傳遞給運行時(shí)系統被叫做拋出異常。
一個(gè)方法拋出異常后,運行時(shí)系統就會(huì )試著(zhù)查找一些方法來(lái)處理它。這些處理異常的可能的方法的集合是被整理在一起的方法列表,這些方法能夠被發(fā)生錯誤的方法調用。這個(gè)方法列表被叫做堆棧調用(call stack)
運行時(shí)系統搜尋包含能夠處理異常的代碼塊的方法所請求的堆棧。這個(gè)代碼塊叫做異常處理器,搜尋首先從發(fā)生的方法開(kāi)始,然后依次按著(zhù)調用方法的倒序檢索調用堆棧。當找到一個(gè)相應的處理器時(shí),運行時(shí)系統就把異常傳遞給這個(gè)處理器。一個(gè)異常處理器要適當地考濾拋出的異常對象的類(lèi)型和異常處理器所處理的異常的類(lèi)型是否匹配。異常被捕獲以后,異常處理器關(guān)閉。如果運行時(shí)系統搜尋了這個(gè)方法的所有的調用堆棧,而沒(méi)有找到相應的異常處理器。
怎么設計異??蚣?br>
任何的異常都是Throwable類(lèi)(為何不是接口??),并且在它之下包含兩個(gè)字類(lèi)Error /Exception,而Error僅在當在Java虛擬機中發(fā)生動(dòng)態(tài)連接失敗或其它的定位失敗的時(shí)候,Java虛擬機拋出一個(gè)Error對象。典型的簡(jiǎn)易程序不捕獲或拋出Errors對象,你可能永遠不會(huì )遇到需要實(shí)例化Error的應用,那就讓我們關(guān)心一下Exception
Exception中比較重要的就是RuntimeException-運行時(shí)異常(當然這個(gè)名字是存在爭議的,因為任何的異常都只會(huì )發(fā)生在運行時(shí)),為什么說(shuō)這個(gè)類(lèi)時(shí)很重要的呢?因為它直接關(guān)系到你的異??蚣艿脑O計,仔細看RuntimeException
Amethod is not required to declare in its throws clause any subclassesof RuntimeException that might be thrown during the execution of themethod but not caught.
-可能在執行方法期間拋出但未被捕獲的 RuntimeException 的任何子類(lèi)都無(wú)需在 throws 子句中進(jìn)行聲明。
也就是說(shuō)你的應用應該不去“關(guān)心”(說(shuō)不關(guān)心是不服責任的,但只是你不應該試圖實(shí)例化它的字類(lèi))RuntimeException,就如同你不應該關(guān)心Error的產(chǎn)生與處理一樣!RuntimeException描述的是程序的錯誤引起來(lái)的,因該由程序負擔這個(gè)責任?。?lt;B>從責任這個(gè)角度看Error屬于JVM需要負擔的責任;RuntimeException是程序應該負擔的責任;checked exception是具體應用負擔的責任</B>)
那就有人會(huì )問(wèn),那我該關(guān)心什么!答案就是除了Error與RuntimeException,其他剩下的異常都是你需要關(guān)心的,而這些異常類(lèi)統稱(chēng)為CheckedException,至于Error與RuntimeException則被統稱(chēng)為Unchecked Exception.
異常的概念就這些了,即使你在網(wǎng)絡(luò )上搜索也就不過(guò)如此,是不是感覺(jué)到有點(diǎn)清晰又有點(diǎn)模糊?那么怎么該如何在這樣單薄而模糊的概念下設計J2EE的異??蚣苣??
解決方案:J2EE異??蚣?br>
我們拿一個(gè)模擬的例子來(lái)說(shuō)明異??蚣艿脑O計過(guò)程,比如我們要對外提供doBusiness()這個(gè)業(yè)務(wù)方法
public void doBusiness() throws xxxBusinessException
當客戶(hù)端調用這樣的方法的時(shí)候應該這樣處理異常(包括處理RuntimeException , checked exception)
<B>記住,無(wú)論如何我們都不希望或者確切的說(shuō)是不應該將RuntimeException這樣的異常暴露給客戶(hù)的,因為他們沒(méi)有解決這個(gè)問(wèn)題的責任!</B>
我們暫時(shí)將Struts中的某個(gè)Action看作時(shí)客戶(hù)端,其中doExecute(....)要調用doBusiness()這個(gè)方法
public void doAction(......)
{
try
{
xxx.doBusiness();
}
catch(Exception e)
{
if(e instanceof RuntimeException)
{
// catch runtime exception
// 你可以在這里將捕獲到的RuntimeException
// 將異常通知給某個(gè)負責此程序的程序員,讓他知道他
// 自己犯了多么低級的錯誤!
}else
{
//checked exception such as xxxBusinessException
//將這樣的異常暴露給客戶(hù)顯示
}
}
}
我們可以這樣設計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;
}
}
而"聰明"的讀者肯定要問(wèn)我那doBusiness()這個(gè)業(yè)務(wù)方法該如何包裝異常呢?
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)
{
// 注意很多應用在這里根本不判斷異常的類(lèi)型而一股腦的采用
// throw new xxxBusinessException(e);
// 而這樣帶來(lái)的問(wèn)題就是xxxBusinessException"吞掉了"RuntimeException
// 從而將checked excption 與unchecked exception混在了一起!
// 其實(shí)xxxBusinessException屬于checked excpetion ,它根本不應該也不能夠理睬RuntimeException
if(! e instanceof RuntimeException) throw new xxxBusinessException(e);
}
}
總結
1。JAVA的異常分為兩類(lèi): checked exception & unchecked excpetion
2。應用開(kāi)發(fā)中產(chǎn)生的異常都應該集成自Exception 但都屬于checked excpetion類(lèi)型
3。應用中的每一層在包裝并傳遞異常的時(shí)候要過(guò)濾掉RuntimeException!
4。從責任這個(gè)角度看Error屬于JVM需要負擔的責任;RuntimeException是程序應該負擔的責任;checked exception 是具體應用負擔的責任
5。無(wú)論如何我們都不希望或者確切的說(shuō)是不應該將RuntimeException這樣的異常暴露給客戶(hù)的,因為他們沒(méi)有解決這個(gè)問(wèn)題的責任!