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