国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

淺析Java語(yǔ)言中兩種異常使用的差別

2019-11-18 14:46:53
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

--------------------------------------------------------------------------------
java提供了兩類主要的異常:runtime exception和checked exception。所有的checked exception是從java.lang.Exception類衍生出來(lái)的,而runtime exception則是從java.lang.RuntimeException或java.lang.Error類衍生出來(lái)的。

它們的不同之處表現(xiàn)在兩方面:機(jī)制上和邏輯上。

一、機(jī)制上

它們?cè)跈C(jī)制上的不同表現(xiàn)在兩點(diǎn):1.如何定義方法;2. 如何處理拋出的異常。請(qǐng)看下面CheckedException的定義:


public class CheckedException extends Exception
{
 public CheckedException() {}
 public CheckedException( String message )
 {
  super( message );
 }
}




以及一個(gè)使用exception的例子:


public class ExceptionalClass
{
 public void method1()
  throws CheckedException
  {
   // ... throw new CheckedException( "...出錯(cuò)了" );
  }
 public void method2( String arg )
  {
   if( arg == null )
   {
    throw new NullPointerException( "method2的參數(shù)arg是null!" );
   }
  }
 public void method3() throws CheckedException
  {
   method1();
  }
}




你可能已經(jīng)注重到了,兩個(gè)方法method1()和method2()都會(huì)拋出exception,可是只有method1()做了聲明。另外,method3()本身并不會(huì)拋出exception,可是它卻聲明會(huì)拋出CheckedException。在向你解釋之前,讓我們先來(lái)看看這個(gè)類的main()方法:


public static void main( String[] args )
{
 ExceptionalClass example = new ExceptionalClass();
 try
 {
  example.method1();
  example.method3();
 }
 catch( CheckedException ex ) { } example.method2( null );
}




在main()方法中,假如要調(diào)用method1(),你必須把這個(gè)調(diào)用放在try/catch程序塊當(dāng)中,因?yàn)樗鼤?huì)拋出Checked exception。

相比之下,當(dāng)你調(diào)用method2()時(shí),則不需要把它放在try/catch程序塊當(dāng)中,因?yàn)樗鼤?huì)拋出的exception不是checked exception,而是runtime exception。會(huì)拋出runtime exception的方法在定義時(shí)不必聲明它會(huì)拋出exception。

現(xiàn)在,讓我們?cè)賮?lái)看看method3()。它調(diào)用了method1()卻沒(méi)有把這個(gè)調(diào)用放在try/catch程序塊當(dāng)中。它是通過(guò)聲明它會(huì)拋出method1()會(huì)拋出的exception來(lái)避免這樣做的。它沒(méi)有捕捉這個(gè)exception,而是把它傳遞下去。實(shí)際上main()方法也可以這樣做,通過(guò)聲明它會(huì)拋出Checked exception來(lái)避免使用try/catch程序塊(當(dāng)然我們反對(duì)這種做法)。

小結(jié)一下:

* Runtime exceptions:

在定義方法時(shí)不需要聲明會(huì)拋出runtime exception;

在調(diào)用這個(gè)方法時(shí)不需要捕捉這個(gè)runtime exception;

runtime exception是從java.lang.RuntimeException或java.lang.Error類衍生出來(lái)的。

* Checked exceptions:

定義方法時(shí)必須聲明所有可能會(huì)拋出的checked exception;

在調(diào)用這個(gè)方法時(shí),必須捕捉它的checked exception,不然就得把它的exception傳遞下去;

checked exception是從java.lang.Exception類衍生出來(lái)的

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 肃南| 寻甸| 女性| 清涧县| 四会市| 泸州市| 图片| 连江县| 故城县| 禹州市| 武功县| 大丰市| 阳朔县| 股票| 泰来县| 慈利县| 南溪县| 湄潭县| 岑溪市| 鹤峰县| 大丰市| 天气| 嘉荫县| 长寿区| 垫江县| 本溪市| 宜章县| 宜宾市| 建平县| 瓦房店市| 孝昌县| 安化县| 鄂托克前旗| 个旧市| 甘洛县| 沾益县| 福建省| 太原市| 民权县| 屏山县| 安国市|