企業應用程序在構建時常常對異常處理關注甚少
在本系列先前的技巧文章中
遠程和命名異常是系統級異常
理論上
嵌套的異常
在設計可靠的異常處理方案時
這些異常完全沒有任何意義
答案是提供一類更有用的異常
清單
import java
import java
public class ApplicationException extends Exception {
/** A wrapped Throwable */
protected Throwable cause;
public ApplicationException() {
super(
}
public ApplicationException(String message) {
super(message);
}
public ApplicationException(String message
super(message);
this
}
// Created to match the JDK
public Throwable initCause(Throwable cause) {
this
return cause;
}
public String getMessage() {
// Get this exception
String msg = super
Throwable parent = this;
Throwable child;
// Look for nested exceptions
while((child = getNestedException(parent)) != null) {
// Get the child
String msg
// If we found a message for the child exception
// we append it
if (msg
if (msg != null) {
msg +=
} else {
msg = msg
}
}
// Any nested ApplicationException will append its own
// children
if (child instanceof ApplicationException) {
break;
}
parent = child;
}
// Return the completed message
return msg;
}
public void printStackTrace() {
// Print the stack trace for this exception
super
Throwable parent = this;
Throwable child;
// Print the stack trace for each nested exception
while((child = getNestedException(parent)) != null) {
if (child != null) {
System
child
if (child instanceof ApplicationException) {
break;
}
parent = child;
}
}
}
public void printStackTrace(PrintStream s) {
// Print the stack trace for this exception
super
Throwable parent = this;
Throwable child;
// Print the stack trace for each nested exception
while((child = getNestedException(parent)) != null) {
if (child != null) {
s
child
if (child instanceof ApplicationException) {
break;
}
parent = child;
}
}
}
public void printStackTrace(PrintWriter w) {
// Print the stack trace for this exception
super
Throwable parent = this;
Throwable child;
// Print the stack trace for each nested exception
while((child = getNestedException(parent)) != null) {
if (child != null) {
w
child
if (child instanceof ApplicationException) {
break;
}
parent = child;
}
}
}
public Throwable getCause() {
return cause;
}
}
清單
異常層次結構
異常層次結構應該從一些十分健壯而又通用的異常入手
因此
清單
import com
public class NoSuchBookException extends ApplicationException {
public NoSuchBookException(String bookName
super(
libraryName +
}
}
當需要編寫大量專用異常時
企業應用程序在構建時通常都不會注意異常處理
From:http://tw.wingwit.com/Article/program/Java/Javascript/201311/25400.html