溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在Java項(xiàng)目中如何實(shí)現(xiàn)自定義異常

發(fā)布時(shí)間:2020-11-11 15:41:32 來源:億速云 閱讀:200 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(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ò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(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)容。

AI