天天看点

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