java中如何創(chuàng)建自定義異常Create Custom Exception
創(chuàng)建自定義異常 Create Custom Exception
馬克-to-win:我們可以創(chuàng)建自己的異常:checked或unchecked異常都可以,規(guī)則如前面我們所介紹,反正如果是checked異常,則必須或者throws,或者catch。到底哪個(gè)好,各路架構(gòu)師大神的意見是50對(duì)50。見我本章后面的附錄。sun公司開始說(shuō),checked異??梢允鼓愕南到y(tǒng)異常語(yǔ)義表達(dá)很清楚。但很多人經(jīng)過一段時(shí)間的實(shí)踐后,馬上表示了異議。checked 異常是java獨(dú)有的,但連Thinking in java的作者都表示,checked異常作為一種java特有的實(shí)驗(yàn)行為,不是很成功。我個(gè)人的意見是:為了達(dá)到解耦的目的,最好繼承 unchecked異常。否則你各種業(yè)務(wù)方法都得throws。將來(lái)業(yè)務(wù)方法一旦改變,還得考慮處理這些throws。(新手可忽略)比如你的業(yè)務(wù)方法a 里如果新加了一句throw受檢異常,而且你還沒有catch,則調(diào)用你這個(gè)a方法的客戶程序?qū)⒈仨毣蛘遚atch或者throws,反正必須做出相應(yīng)調(diào)整。如果當(dāng)初你的a方法里只是拋出一個(gè)非受檢異常,客戶程序就不用做任何調(diào)整了。
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
例1.9.1-本章源碼
public class Test {
public static void main(String args[]) throws RelationshipExceptionMark_to_win {
int talkTimesPerDay = 2;
if (talkTimesPerDay < 3) {
RelationshipExceptionMark_to_win e = new RelationshipExceptionMark_to_win();
e.setMsg("每天說(shuō)話小于3 次,拋出關(guān)系異常的異常,分手");
System.out.println("馬克-to-win:here");
throw e;
}
System.out.println("馬克-to-win:優(yōu)雅結(jié)束");
}
}
class RelationshipExceptionMark_to_win extends Exception {
String msg;
String getMsg() {
return msg;
}
void setMsg(String msg) {
this.msg = msg;
}
}
輸出結(jié)果:
馬克-to-win:here
Exception in thread "main" RelationshipExceptionMark_to_win
at Test.main(Test.java:5)
例1.9.2-本章源碼
public class Test {
public static void main(String args[]) {
int talkTimesPerDay = 2;
if (talkTimesPerDay < 3) {
RelationshipExceptionMark_to_win e = new RelationshipExceptionMark_to_win();
e.setMsg("每天說(shuō)話小于3 次,拋出關(guān)系異常的異常,分手");
throw e;
}
System.out.println("馬克-to-win:優(yōu)雅結(jié)束");
}
}
class RelationshipExceptionMark_to_win extends RuntimeException {
String msg;
String getMsg() {
return msg;
}
void setMsg(String msg) {
this.msg = msg;
}
}
輸出結(jié)果:
Exception in thread "main" RelationshipExceptionMark_to_win
at Test.main(Test.java:5)
例1.9.3-本章源碼
public class Test {
public static void main(String args[]) {
int talkTimesPerDay = 2;
try {
if (talkTimesPerDay < 3) {
RelationshipExceptionMark_to_win e = new RelationshipExceptionMark_to_win();
e.setMsg("每天說(shuō)話小于3 次,拋出關(guān)系異常的異常,分手");
throw e;
}
} catch (RelationshipExceptionMark_to_win e1) {
System.out.println(e1.getMsg());
}
System.out.println("馬克-to-win:優(yōu)雅結(jié)束");
}
}
class RelationshipExceptionMark_to_win extends Exception {
String msg;
String getMsg() {
return msg;
}
void setMsg(String msg) {
this.msg = msg;
}
}
輸出結(jié)果:
每天說(shuō)話小于3 次,拋出關(guān)系異常的異常,分手
馬克-to-win:優(yōu)雅結(jié)束