淺析Java語言中存在兩種主要異常的差別

來源:互聯網
上載者:User

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

它們的不同之處表現在兩方面:機制上和邏輯上。

一、機制上

它們在機制上的不同表現在兩點:1.如何定義方法;2. 如何處理拋出的異常。請看下面CheckedException的定義:

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

以及一個使用exception的例子:

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

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

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

在main()方法中,如果要調用method1(),你必須把這個調用放在try/catch程式塊當中,因為它會拋出Checked exception。

相比之下,當你調用method2()時,則不需要把它放在try/catch程式塊當中,因為它會拋出的exception不是checked exception,而是runtime exception。會拋出runtime exception的方法在定義時不必聲明它會拋出exception。

現在,讓我們再來看看method3()。它調用了method1()卻沒有把這個調用放在try/catch程式塊當中。它是通過聲明它會拋出method1()會拋出的exception來避免這樣做的。它沒有捕獲這個exception,而是把它傳遞下去。實際上main()方法也可以這樣做,通過聲明它會拋出Checked exception來避免使用try/catch程式塊(當然我們反對這種做法)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.