您的位置:首页 > 其它

try-catch-finally块的执行流程

2015-10-23 00:02 78 查看
记得前些天看try-catch-finally的东西,在很多博客上看了很多文章,也没有理解的很透彻,今天看到了国外的一个牛人讲的,感觉非常好非常透彻,完全没有云里雾里的感觉,就把它翻译过来。

在这篇文中我们来看一下怎么使用try-catch-finally块来进行异常处理,在看这个之前可以先看一下try-catch

try-catch块的流程控制

当异常不发生的时候:

当在try块中的语句没有抛出异常的时候,catch永远不会被执行。

例如:

.....
int x = 10;
int y = 10;
try{
int num= x/y;
System.out.println("next-statement: Inside try block");
}catch(Exception ex)
{
System.out.println("Exception");
}
System.out.println("next-statement: Outside of try-catch");
...


输出结果:

next-statement: Inside try block
next-statement: Outside of try-catch


上边的例子中没有异常发生,所以catch没有执行

当异常发生的情况:

int x = 0;
int y = 10;
try{
int num= y/x;
System.out.println("next-statement: Inside try block");
}catch(Exception ex)
{
System.out.println("Exception Occurred");
}
System.out.println("next-statement: Outside of try-catch");
...


输出结果:

Exception Occurred
next-statement: Outside of try-catch


在上边的例子中,有两条语句在try块中,因为异常发生在第一条语句中,所以第二条语句没有被执行,因此我们可以总结:一旦异常发生try块中剩下的语句不会被执行同时执行控制也被传递到catch块中。

try/catch/finally块的流程控制:

1、如果在try块中发生异常那么控制会立刻被传递(跳过try块中的剩下的其他语句)到catch中去。一旦catch块执行完成之后finally块和其后的程序执行

2、如果在代码中没有异常发生,try块中的代码会被完全执行,然后执行控制被传递到(跳过catch块)finally块中

3、如果在catch或者try块中有return语句,在这种情况下,finally也会执行,控制流是:先执行finally然后回到return语句。

考虑下边的代码理解上边的观点:

class TestExceptions {
static void myMethod(int testnum) throws Exception {
System.out.println ("start - myMethod");
if (testnum == 12)
throw new Exception();
System.out.println("end - myMethod");
return;
}
public static void main(String  args[]) {
int testnum = 12;
try {
System.out.println("try - first statement");
myMethod(testnum);
System.out.println("try - last statement");
}
catch ( Exception ex) {
System.out.println("An Exception");
}
finally {
System. out. println( "finally") ;
}
System.out.println("Out of try/catch/finally - statement");
}
}


输出结果:

try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement


关于return和finally谁先返回的问题,请看这篇文章,点击

原文地址:http://beginnersbook.com/2013/05/flow-in-try-catch-finally/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: