1、如何捕獲異常
瞭解什麼是異常看這裏:什麼是java中的異常
捕獲的方法是使用try/catch關鍵字。將可能產生異常,並且需要捕獲的代碼塊使用try/catch圍繞,如果產生了異常即可捕獲到,將直接中斷try代碼塊,同時執行catch代碼塊。
try/catch中的代碼被稱爲受保護的代碼(Protected code)。
try/catch語法:
-
try
-
{
-
-
}catch(ExceptionName e1)
-
{
-
-
}
如果受保護的代碼發生了異常,該異常的數據類型與ExceptionName匹配,則異常會被作爲catch代碼塊的參數傳遞到catch代碼塊中,並執行catch代碼塊。
例子:
-
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]);
-
}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
2、如何使用多個catch
一個try後面可以跟任意多個catch。
語法:
-
try
-
{
-
-
}catch(ExceptionType1 e1)
-
{
-
-
}catch(ExceptionType2 e2)
-
{
-
-
}catch(ExceptionType3 e3)
-
{
-
-
}
如果受保護的代碼發生了異常,該異常被拋出到第一個catch塊。如果異常的數據類型與ExceptionType1匹配,它就會被第一個catch捕獲。如果不是,則該異常傳遞到第二個catch語句。以此類推,直到異常被捕獲或全未匹配。若全未捕獲,則終止執行,並將異常拋至調用堆棧中。
例子:
-
import java.io.*;
-
public class ExceptionTest{
-
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