您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)在Java項(xiàng)目中如何實(shí)現(xiàn)自定義異常,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
自定義異常
class ChushulingException extends Exception { public ChushulingException(String msg) { super(msg); } } class ChushufuException extends Exception { public ChushufuException(String msg) { super(msg); } }
自定義異常 End
class Numbertest { public int shang(int x,int y) throws ChushulingException,ChushufuException { if(y<0) { throw new ChushufuException("您輸入的是"+y+",規(guī)定除數(shù)不能為負(fù)數(shù)!");//拋出異常 } if(y==0) { throw new ChushulingException("您輸入的是"+y+",除數(shù)不能為0!"); } int m=x/y; return m; } } class Rt001 { public static void main(String[]args) { Numbertest n=new Numbertest(); //捕獲異常 try { System.out.println("商="+n.shang(1,-3)); } catch(ChushulingException yc) { System.out.println(yc.getMessage()); yc.printStackTrace(); } catch(ChushufuException yx) { System.out.println(yx.getMessage()); yx.printStackTrace(); } catch(Exception y) { System.out.println(y.getMessage()); y.printStackTrace(); } finally{ System.out.println("finally!");} ////finally不管發(fā)沒發(fā)生異常都會(huì)被執(zhí)行 } } /*
[總結(jié)]
1.自定義異常:
class 異常類名 extends Exception { public 異常類名(String msg) { super(msg); } }
2.標(biāo)識(shí)可能拋出的異常:
throws 異常類名1,異常類名2
3.捕獲異常:
try{} catch(異常類名 y){} catch(異常類名 y){}
4.方法解釋
getMessage() //輸出異常的信息 printStackTrace() //輸出導(dǎo)致異常更為詳細(xì)的信息
關(guān)于在Java項(xiàng)目中如何實(shí)現(xiàn)自定義異常就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。