JAVA異常處理

來源:互聯網
上載者:User

標籤:cat   except   變數   技術分享   http   []   str   trace   異常聲明   

朋友去面試問了好多異常處理的問題,日常工作中遇到的還不夠解釋,這裡寫個文章講解一下。

(1)運行時異常(checked exception):繼承自java.lang. RuntimeException類

常見5種:

ClassCastException(類型轉換異常)

IndexOutOfBoundsException(數組越界)

NullPointerException(null 指標)

ArrayStoreException(資料存放區異常,運算元組時類型不一致)

還有IO操作的BufferOverflowException異常

(2)非運行時異常(unchecked exception):繼承自java.lang.Exception類

常見:

Java.lang.ClassNotFoundException

Java.lang.NoSuchMetodException

java.io.IOException

先給出文法:

try{     //try塊中放可能發生異常的代碼。     //如果執行完try且不發生異常,則接著去執行finally塊和finally後面的代碼(如果有的話)。     //如果發生異常,則嘗試去匹配catch塊。 }catch(SQLException SQLexception){    //每一個catch塊用於捕獲並處理一個特定的異常,或者這異常類型的子類。Java7中可以將多個異常聲明在一個catch中。    //catch後面的括弧定義了異常類型和異常參數。如果異常與之匹配且是最先匹配到的,則虛擬機器將使用這個catch塊來處理異常。    //在catch塊中可以使用這個塊的異常參數來擷取異常的相關資訊。異常參數是這個catch塊中的局部變數,其它塊不能訪問。    //如果當前try塊中發生的異常在後續的所有catch中都沒捕獲到,則先去執行finally,然後到這個函數的外部caller中去匹配異常處理器。    //如果try中沒有發生異常,則所有的catch塊將被忽略。 }catch(Exception exception){    //...}finally{     //finally塊通常是可選的。   //無論異常是否發生,異常是否匹配被處理,finally都會執行。   //一個try至少要有一個catch塊,否則, 至少要有1個finally塊。但是finally不是用來處理異常的,finally不會捕獲異常。  //finally主要做一些清理工作,如流的關閉,資料庫連接的關閉等。 }

public class Class1 {

public static void main(String[] args) throws Exception {
try {
List<String> list = new ArrayList<String>();
Class2 c = new Class2();
c.aa(list);
System.out.println("列印");
}catch(Exception e) {
System.out.println(">>>>>>>>>>>main");
e.printStackTrace();
}finally {
System.out.println("main finally");
}
}

}

public class Class2 {
public String aa(List<String> list) throws Exception{
try {
list.get(10);
}catch(Exception e) {
System.out.println(">>>>>>class2 aa="+e.getMessage());
e.printStackTrace();
throw e; //必須throw調用方法還會停止向下運行,並被呼叫者法接住並拋出
}finally {
System.out.println("finally");
}
return null;
}
}

JAVA異常處理

聯繫我們

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