Java Custom Exception Example(Java自定義異常案例)

轉(zhuǎn)譯自:https://examples.javacodegeeks.com
本文在已發(fā)布在GitHub(https://github.com/clxering/Technical-Articles-Collection/blob/master/Java-Custom-Exception-Example.md)歡迎糾錯(cuò)訂正

In this example we will look briefly(短暫的) at the basics of Exception, in Java Programming Language. We will also see, how to create a custom Exception Class.

在這個(gè)案例中呢撞,我們將使用Java語言來簡要介紹“異澈笫遥”的基礎(chǔ)知識(shí)辕羽。我們同樣也能夠了解如何創(chuàng)建一個(gè)自定義的Exception類。

1、Basics of Exception(異常的基礎(chǔ)知識(shí))

As per(按照) oracle docs, An exception is an event, which occurs during the execution of a program, that disrupts(擾亂) the normal flow of the program’s instructions(指令).

按照oracle的文檔介紹守屉,異常是一個(gè)在程序運(yùn)行期間發(fā)生的事件隅忿,會(huì)擾亂正常程序流程的指令。

In laymen(非專業(yè)人員) terms, when a condition occurs, in which the routine(程序) is not sure how to proceed in an ordinary way it creates an object of exception and hands it over to the runtime system to find an appropriate handler for the exception object. In case, the runtime system does not find an appropriate handler in the call hierarchy the runtime system terminates.

用非專業(yè)的話來說入客,當(dāng)滿足異常發(fā)生條件時(shí),程序不確定能以普通的方式進(jìn)行時(shí)腿椎,它創(chuàng)建一個(gè)異常對(duì)象并遞交給運(yùn)行時(shí)系統(tǒng)桌硫,以查找處理異常對(duì)象的合適的處理程序。在這種情況下啃炸,運(yùn)行時(shí)系統(tǒng)在運(yùn)行時(shí)系統(tǒng)終止的調(diào)用層次結(jié)構(gòu)中沒有找到合適的處理程序铆隘。

The exceptions have java.lang.Throwable as their superclass.The three main categories of Exceptional conditions are :

異常以java.lang.Throwable類作為父類。異常主要有三大類:

(1)Error(represented by java.lang.Error and its sub-classes)

錯(cuò)誤(以java.lang.Error類及其子類表示)

(2)Checked Exception(represented by direct subclasses of java.lang.Exception except java.lang.RuntimeException)

Checked異常(由java.lang.Exception除了java.lang.RuntimeException類的子類表示)

(3)Unchecked or Runtime Exceptions (represented by java.lang.RuntimeException and its sub-classes)

Unchecked或運(yùn)行時(shí)異常(由java.lang.RuntimeException類及其子類表示)

Errors : Errors denote serious abnormal(不正常的) condition with the application like OutOfMemoryError or VirtualMachineError. Any reasonable application should not try to recover from such a condition.

錯(cuò)誤表示嚴(yán)重的異常情況南用,如OutOfMemoryError(內(nèi)存溢出)或VirtualMachineError(虛擬機(jī)錯(cuò)誤)膀钠。任何理由都不能使應(yīng)用程序從這種情況中恢復(fù)過來。

Runtime Exception/Unchecked Exception : These types of exceptions usually indicate programming errors like NullPointerException or IllegalArgumentException. The application may or may not choose to recover from the condition.

這些類型的異常通常表示程序錯(cuò)誤裹虫,如NullPointerException(空指針異常)或IllegalArgumentException(參數(shù)異常)肿嘲。應(yīng)用程序可以選擇從該類異常中恢復(fù),也可以選擇不恢復(fù)筑公。

Checked Exception : An application is supposed to catch these types of exceptions and recover reasonably from them. Examples include FileNotFoundException and ParseException.

應(yīng)用程序應(yīng)該捕獲這類異常并合理恢復(fù)雳窟。例如FileNotFoundException(文件未找到異常)和ParseException(解析異常)。

2匣屡、Creating custom Exception(創(chuàng)建自定義異常)

The first thing before creating a custom exception, the developer should be able to justify(證明) the creation(創(chuàng)建封救,n.). As per(按照) Java Docs, You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s.

創(chuàng)建自定義異常前拇涤,開發(fā)者應(yīng)為此(行為)找到依據(jù)。按照J(rèn)ava文檔誉结,如果你對(duì)以下任何一個(gè)問題回答yes鹅士,你應(yīng)該編寫自己的異常類;否則惩坑,你(最好)用別人的如绸。

(1)Do you need an exception type that isn’t represented by those in the Java platform?

你需要一個(gè)Java平臺(tái)中沒有(定義)的異常類型嗎?

(2)Would it help users if they could differentiate(區(qū)分) your exceptions from those thrown by classes written by other vendors(供應(yīng)商)?

如果用戶可以將你的異常與其他供應(yīng)商編寫的類拋出的異常區(qū)分開來旭贬,那么這會(huì)對(duì)用戶有幫助嗎?

(3)Does your code throw more than one related exception?

您的代碼是否會(huì)拋出多個(gè)相關(guān)異常怔接?

(4)If you use someone else’s exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

如果你使用其他人的異常,用戶是否可以訪問這些異常稀轨?類似的問題是扼脐,你的包應(yīng)該是獨(dú)立的、自包含的嗎奋刽?

Now, that you are sure that you really do want a create a custom Exception class we will begin writing the actual program.To create a custom checked exception, we have to sub-class from the java.lang.Exception class. And that’s it! Yes, creating a custom exception in java is simple as that!

現(xiàn)在瓦侮,您確信您確實(shí)想要?jiǎng)?chuàng)建一個(gè)自定義的異常類,我們將開始編寫實(shí)際的程序佣谐。要?jiǎng)?chuàng)建一個(gè)自定義異常肚吏,我們必須從java.lang.Exception派生子類。是的狭魂,在java中創(chuàng)建一個(gè)自定義異常很簡單罚攀!

public class CustomException extends Exception{}

Sometimes though, the CustomException object will have to be constructed from another exception. So its important that we create a constructor for such a scenario.

但有時(shí),CustomException對(duì)象需要通過另一個(gè)異常來構(gòu)造雌澄。因此斋泄,為這樣的場景創(chuàng)建構(gòu)造函數(shù)是很重要的。

So a more complete class would be as below :

因此镐牺,一個(gè)更完整的類應(yīng)如下所示:

CustomException.java:

package com.javacodegeeks.examples.exception;
public class CustomException extends Exception
{
    private static final long serialVersionUID = 1997753363232807009L;
        public CustomException()
        {}
        public CustomException(String message)
        {
            super(message);
        }
        public CustomException(Throwable cause)
        {
            super(cause);
        }
        public CustomException(String message, Throwable cause)
        {
            super(message, cause);
        }
        public CustomException(String message, Throwable cause, 
                         boolean enableSuppression, boolean writableStackTrace)
        {
            super(message, cause, enableSuppression, writableStackTrace);
        }
}

2.1炫掐、Testing the custom Exception(測試自定義異常) :
CustomExceptionTest.java:

package com.javacodegeeks.examples.exception;
public class CustomExceptionTest
{
    public static void main(String[] args)
    {
    try
        {
          testException(null);
        }
        catch (CustomException e)
        {
          e.printStackTrace();
        }
    }
    public static void testException(String string) throws CustomException
    {
          if(string == null)
            throw new CustomException("The String value is null");
    }
}

Similarly, an unchecked exception can be created by sub-classing from the java.lang.RuntimeException Class.

類似地,unchecked異巢墙В可以通過java.lang.RuntimeException的子類來創(chuàng)建募胃。

public class CustomException extends RuntimeException{...}

3、Points to note(注意事項(xiàng))

(1)An unchecked exception should be preferred(首選) to a checked exception. This will help programmes to be free of unnecessary try..catch blocks.

相比一個(gè)unchecked異常畦浓,應(yīng)首選checked異常痹束。這有助于程序擺脫不必要的try..catch塊。

(2)Exceptions are abnormal conditions, and as such should not be used for controlling the flow of execution of the programmes(as demonstrated by example below).

異常是異常情況宅粥,不應(yīng)該用于程序的流程控制(如下面示例所示)参袱。

try
{
    for (int i = 0;; i++)
    {
        System.out.println(args[i]);
    }
}
catch (ArrayIndexOutOfBoundsException e)
{
        // do nothing
}

(3)A catch block should not be empty as shown in the example above. Such exceptions are very difficult to track(跟蹤), since there is no logging.

catch塊不應(yīng)該是空的,如上面的示例所示。由于沒有日志記錄抹蚀,因此很難跟蹤這些異常剿牺。

(4)The name of a custom exception class should end with Exception. It improves the readability of the code. Instead of naming the class InvalidSerial, the class should be named InvalidSerialException.

自定義異常類的名稱應(yīng)該以Exception結(jié)尾。它提高了代碼的可讀性环壤。類不應(yīng)該命名為InvalidSerial晒来,而應(yīng)該命名為InvalidSerialException。

(5)When using ARM/try-with-resources blocks, if exception gets suppressed by the try-with-resources statement, we can use Throwable#getSuppressed() method.

當(dāng)使用ARM/try-with-resources塊時(shí)郑现,如果異常被try-with-resources語句抑制湃崩,我們可以使用Throwable# getrepression()方法。

4接箫、Closing Words(結(jié)束語)

Here,we tried to understand the basics of exception and how to create a custom exception of our own. We learned the best practices while creating a custom exception class and also how to handle(處理) an exception in a reasonable manner.

在這里攒读,我們嘗試?yán)斫猱惓5幕驹恚约叭绾蝿?chuàng)建我們自己的自定義異常辛友。我們在創(chuàng)建自定義異常類時(shí)學(xué)習(xí)了最佳實(shí)踐薄扁,以及如何以合理的方式處理異常。

附錄废累,相關(guān)資料1(可與上述轉(zhuǎn)譯內(nèi)容互參)

Throwable是所有Java中所有異常類的父類邓梅,有兩種子類:ErrorException

1、Error: 表示由JVM所偵測到的無法預(yù)期的錯(cuò)誤邑滨,由于這是屬于JVM層次的嚴(yán)重錯(cuò)誤日缨,導(dǎo)致JVM無法繼續(xù)執(zhí)行,這是不可捕捉到的掖看,無法采取任何恢復(fù)的操作匣距,只能顯示錯(cuò)誤信息。Error類體系描述了Java運(yùn)行系統(tǒng)中的內(nèi)部錯(cuò)誤以及資源耗盡的情形乙各,應(yīng)用程序不應(yīng)該拋出這種類型的對(duì)象(一般是由虛擬機(jī)拋出)墨礁。假如出現(xiàn)這種錯(cuò)誤,除了盡力使程序安全退出外耳峦,在其他方面是無能為力的。

2焕毫、Exception: 表示可恢復(fù)的異常蹲坷,這是可捕捉到的。Java提供了兩類主要的異常:Runtime Exception和checked exception邑飒。

(2-1)checked 異常是經(jīng)常遇到的循签,如:IO異常、SQL異常疙咸。對(duì)于這種異常县匠,JAVA編譯器強(qiáng)制要求我們對(duì)出現(xiàn)的這些異常進(jìn)行catch。所以,面對(duì)這種異常只能編寫catch塊去處理乞旦。這類異常一般是外部錯(cuò)誤贼穆,例如試圖從文件尾后讀取數(shù)據(jù)等,這并不是程序本身的錯(cuò)誤兰粉,而是在應(yīng)用環(huán)境中出現(xiàn)的外部錯(cuò)誤故痊。

(2-2)Runtime Exception也稱運(yùn)行時(shí)異常,我們可以不處理玖姑。當(dāng)出現(xiàn)這樣的異常時(shí)愕秫,總是由虛擬機(jī)接管。比如:我們從來沒有人去處理過NullPointerException異常焰络,它就是運(yùn)行時(shí)異常戴甩,并且NullPointerException還是最常見的異常之一。Runtime Exception體系包括錯(cuò)誤的類型轉(zhuǎn)換闪彼、數(shù)組越界訪問和試圖訪問空指針等等甜孤。如果出現(xiàn)Runtime Exception,那么一定是程序員的錯(cuò)誤备蚓。例如:可以通過檢查數(shù)組下標(biāo)和數(shù)組邊界來避免數(shù)組越界訪問異常课蔬。

出現(xiàn)運(yùn)行時(shí)異常后,系統(tǒng)會(huì)把異常一直往上層拋郊尝,一直遇到處理代碼二跋。如果到最上層還沒有處理塊,多線程程序就由Thread.run()拋出流昏,這個(gè)線程就退出扎即;如果是單線程就被main()拋出,整個(gè)程序也就退出了况凉。運(yùn)行時(shí)異常是Exception的子類谚鄙,也有一般異常的特點(diǎn),是可以被catch塊處理的刁绒。只不過往往我們不對(duì)他處理罷了闷营。如果不對(duì)運(yùn)行時(shí)異常進(jìn)行處理,那么出現(xiàn)運(yùn)行時(shí)異常之后知市,要么是線程中止傻盟,要么是主程序終止。

如果不想終止線程或程序嫂丙,則必須捕捉所有的運(yùn)行時(shí)異常娘赴,決不讓這個(gè)處理線程退出。隊(duì)列里面出現(xiàn)異常數(shù)據(jù)了跟啤,正常的處理應(yīng)該是把異常數(shù)據(jù)舍棄诽表,然后記錄日志烈拒。不應(yīng)該由于異常數(shù)據(jù)而影響下面對(duì)正常數(shù)據(jù)的處理眷蜓。但并不代表在所有的場景你都應(yīng)該如此,如果在其它場景,遇到了一些錯(cuò)誤舟奠,如果退出程序比較好胆剧,這時(shí)你就可以不太理會(huì)運(yùn)行時(shí)異常骇塘,或者是通過對(duì)異常的處理顯式的控制程序退出汛闸。異常處理的目標(biāo)之一就是為了把程序從異常中恢復(fù)出來。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末平痰,一起剝皮案震驚了整個(gè)濱河市汞舱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌宗雇,老刑警劉巖昂芜,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異赔蒲,居然都是意外死亡泌神,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門舞虱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來欢际,“玉大人,你說我怎么就攤上這事矾兜∷鹎鳎” “怎么了?”我有些...
    開封第一講書人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵椅寺,是天一觀的道長浑槽。 經(jīng)常有香客問我,道長返帕,這世上最難降的妖魔是什么桐玻? 我笑而不...
    開封第一講書人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮荆萤,結(jié)果婚禮上镊靴,老公的妹妹穿的比我還像新娘。我一直安慰自己链韭,他們只是感情好邑闲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著梧油,像睡著了一般。 火紅的嫁衣襯著肌膚如雪州邢。 梳的紋絲不亂的頭發(fā)上儡陨,一...
    開封第一講書人閱讀 51,573評(píng)論 1 305
  • 那天褪子,我揣著相機(jī)與錄音,去河邊找鬼骗村。 笑死嫌褪,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的胚股。 我是一名探鬼主播笼痛,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼琅拌!你這毒婦竟也來了缨伊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤进宝,失蹤者是張志新(化名)和其女友劉穎刻坊,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體党晋,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡谭胚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了未玻。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片灾而。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖扳剿,靈堂內(nèi)的尸體忽然破棺而出旁趟,到底是詐尸還是另有隱情,我是刑警寧澤舞终,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布轻庆,位于F島的核電站,受9級(jí)特大地震影響敛劝,放射性物質(zhì)發(fā)生泄漏余爆。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一夸盟、第九天 我趴在偏房一處隱蔽的房頂上張望蛾方。 院中可真熱鬧,春花似錦上陕、人聲如沸桩砰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽亚隅。三九已至,卻和暖如春庶溶,著一層夾襖步出監(jiān)牢的瞬間煮纵,已是汗流浹背懂鸵。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留行疏,地道東北人匆光。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像酿联,于是被迫代替她去往敵國和親终息。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評(píng)論 0 10
  • 幾只麻雀嘰嘰喳喳 我在樹下洗頭發(fā) 夏天終于來了 我可以穿上短袖贞让,單褲 渾身頓感一輕了 再也不用時(shí)刻放著冬衣 以防時(shí)...
    饅頭小米粥閱讀 183評(píng)論 0 0
  • 【目錄】 —18— 遇到小祥哥的那年周崭,狗子旦不過才四十出頭,但是正旦這個(gè)行當(dāng)不像其它角色震桶,對(duì)人的要求太高休傍,嗓音婉轉(zhuǎn)...
    聽風(fēng)閣主人閱讀 478評(píng)論 0 4