java基礎面試題:運行時異常與一般異常有何異同?error和exception有什麼區別? 請寫出你最常見到的5個runtimeexception?,

來源:互聯網
上載者:User

java基礎面試題:運行時異常與一般異常有何異同?error和exception有什麼區別? 請寫出你最常見到的5個runtimeexception?,

Throwable是Java錯誤處理的父類,有兩個子類:Error和Exception。

 

Error:無法預期的嚴重錯誤,導致JVM虛擬機器無法繼續執行,幾乎無法恢複捕捉的

Exception:可恢複捕捉的。java健壯程式的手段。

 

Java提供了兩類主要的異常:runtime exception和checked exception (編譯時間被檢查的異常)。

checked exception (編譯時間被檢查的異常):JAVA編譯器強制要求我們必需對出現的這些異常進行catch或throws。所以,面對這種異常不管我們是否願意,只能寫一大堆catch塊或throws去處理可能的異常。

如IO異常,以及SQL異常等。

runtime exception:編譯通過,但運行通不過,出現RuntimeException,通常是程式員出錯。虛擬機器接管會終止線程或主程式。如錯誤的類型轉換、數組越界訪問和訪問null 指標等

最常見到的runtime exception

1、NullPointerException:

int a1[]=null;
System.out.print(a1[2]);

2、ArrayIndexOutOfBoundsException

int a[]={2,3,5,32,6};
for (int i = 0; i <6; i++)
{
System.out.print(a[i]);
}

3、ClassCastException

Object i=new Integer(1);
System.out.println((String)i);

4、ArithmeticException

int a=5/0;

5、NegativeArraySizeException

String[] s=new String[-10];

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.