首页 > 代码库 > java基础---->Java中异常的使用(二)

java基础---->Java中异常的使用(二)

  这一篇博客用例子讲述一下异常的处理过程。

异常的执行过程

一、实例一:return语句

public class ExceptionTest_1 {    public static void main(String[] args) {        int result = 0;        try {            System.out.println("before result");            result = 9 / 0;            System.out.println("after result");        } catch (Exception e) {            System.out.println("exception" + e.getMessage() + ", result: " + result);            return;        } finally {            System.out.println("final execute, " + result);        }        System.out.println("out of try statement, " + result);    }}

执行的结果如下:

before resultexception/ by zero, result: 0final execute, 0

将上述代码result = 9 / 0改为 result = 9 / 2;也就是不产生异常,执行的结果如下:

before resultafter resultfinal execute, 4out of try statement, 4

 

二、实例二:try里面有try语句

public class ExceptionTest_2 {    public static void main(String[] args) {        try {            if (1 + 2 > 2) {                throw new FileNotFoundException();            }            try {                throw new FileNotFoundException();            } catch (FileNotFoundException e) {                System.out.println("world hello");            }        } catch (Exception e) {            System.out.println("hello world");        } finally {            System.out.println("final action");        }    }}

执行的结果如下:

hello worldfinal action

如果将if(1 + 2 > 2)改变if(1 + 2 > 4),也就是try块里面没有抛出异常。执行的结果如下:

world hellofinal action

 简短的异常说明:

当抛出异常后,会发生以下的事情。1、用new在堆上创建异常对象,当前的执行路径被终止,并从当前环境中弹出异常对象的引用。2、异常处理机制接管程序,并寻找一个恰当的地方继续执行程序。3、如果有定义了final,那么会执行final块的代码。

 

友情链接

  • 详细的异常说明:http://blog.csdn.net/hguisu/article/details/6155636

 

java基础---->Java中异常的使用(二)