天天看點

Java千百問_04異常處理(002)_java如何捕獲異常

捕獲的方法是使用try/catch關鍵字。将可能産生異常,并且需要捕獲的代碼塊使用try/catch圍繞,如果産生了異常即可捕獲到,将直接中斷try代碼塊,同時執行catch代碼塊。

try/catch中的代碼被稱為受保護的代碼(protected code)。

try/catch文法:

Java千百問_04異常處理(002)_java如何捕獲異常

try  

{  

//protected code  

}catch(exceptionname e1)  

//catch block  

}  

如果受保護的代碼發生了異常,該異常的資料類型與exceptionname比對,則異常會被作為catch代碼塊的參數傳遞到catch代碼塊中,并執行catch代碼塊。

例子:

Java千百問_04異常處理(002)_java如何捕獲異常

import java.io.*;  

public class exceptiontest{  

public static void main(string args[]){  

try{  

int a[] = new int[2];  

system.out.println("access element three :" + a[3]);//數組隻有2個元素,通路第三個時會發生arrayindexoutofboundsexception異常  

}catch(arrayindexoutofboundsexception e){  

system.out.println("exception thrown :" + e);  

system.out.println("out of the block");  

這将産生以下結果:

exception thrown :java.lang.arrayindexoutofboundsexception: 3

out of the block

一個try後面可以跟任意多個catch。

文法:

Java千百問_04異常處理(002)_java如何捕獲異常

}catch(exceptiontype1 e1)  

}catch(exceptiontype2 e2)  

}catch(exceptiontype3 e3)  

如果受保護的代碼發生了異常,該異常被抛出到第一個catch塊。如果異常的資料類型與exceptiontype1比對,它就會被第一個catch捕獲。如果不是,則該異常傳遞到第二個catch語句。以此類推,直到異常被捕獲或全未比對。若全未捕獲,則終止執行,并将異常抛至調用堆棧中。

Java千百問_04異常處理(002)_java如何捕獲異常

  public static void main(string args[]){  

        try {  

            fileinputstream file = new fileinputstream("/usr/test");  

            byte x = (byte) file.read();  

        } catch (ioexception i) {  

            system.out.println("ioexception thrown  :" + i);  

        } catch (nullpointerexception f) {  

            system.out.println("nullpointerexception thrown  :" + f);  

        }  

        system.out.println("catch");  

ioexception thrown :java.io.filenotfoundexception: /usr/test (no such file or directory)

catch

原文位址:http://blog.csdn.net/ooppookid/article/details/51088832