qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Java异常发生时程序的执行顺序

 一些基础知识:
  1.try代码段包含可能产生例外的代码;
  2.try代码段后跟有一个或多个代码段;
  3.每个catch代码段声明其能处理的一种特定的异常并提供处理的方法;
  4.当异常发生时,程序会终止当前的流程,根据获取异常的类型去执行相应的catch代码段,有多个符合条件的catch时,只执行第一个;
  5.finally段的代码无论是否发生异常都会执行。
  6.在一个try语句块中,基类异常的捕获语句不可以写在子类异常捕获语句的上面。
  看一个例子:
/**
* @author Lansine
*
*/
public class T1 {
/**
* @param args
*/
public static void main(String[] args) {
String s = "1";
try {
s = "2";
System.out.println(s);
if (s == "2")
throw new Exception("h");
} catch (Exception e) {
s = "3";
System.out.println(s);
} finally {
s = "4";
System.out.println(s);
}
s = "5";
System.out.println(s);
}
}
  输出的结果是2,3,4,5    (这里的逗号只用于显示)。上述语句非常清楚,但是在上述结构中加上return,就变得有些复杂了,如
/**
* @author Lansine
*
*/
public class T2 {
/**
* @param args
*/
public static void main(String[] args) {
String s = "1";
try {
s = "2";
System.out.println(s);
return;
} catch (Exception e) {
s = "3";
System.out.println(s);
} finally {
s = "4";
System.out.println(s);
}
s = "5";
System.out.println(s);
}
}
输出的结果是2,4也就是说在try结构中,虽然使用了return语句强制函数返回,不再往下执行,但实现上finally中的还是执行了。但除了finally外的其它语句不再被执行。
  一个更流行的例子是:
import java.io.*;
/**
* @author Lansine
*
*/
public class Mine {
public static void main(String argv[]){
Mine m = new Mine();
try {
System.out.println(m.amethod());
} catch (Exception e) {
// TODO 自动生成 catch 块
//e.printStackTrace();
System.out.println("我知道了");
}
System.out.println("finished");
}
public int amethod()throws Exception {
try {
FileInputStream dis = new FileInputStream("Hello.txt"); // 1,抛出异常
System.out.println("异常发生之后");
} catch (Exception ex) {
System.out.println("No such file found"); // 2.catch捕捉异常,并执行
//throw new Exception("上面处理");
return -1; // 4,return 返回
} finally {
System.out.println("Doing finally"); // 3.finally一定会执行,在return之前。
}
System.out.println("在代码后面");
return 0;
}
}
  结果是:
  No such file found
  Doing finally
  -1
  finished
  如果在catch块中抛出异常,则结果为:
  No such file found
  Doing finally
  我知道了
  finished
  注意:如果异常往上抛直到main函数还没有被catch处理的话,程序将被异常终止。

posted on 2014-07-02 16:38 顺其自然EVO 阅读(318) 评论(0)  编辑  收藏 所属分类: 测试学习专栏


只有注册用户登录后才能发表评论。


网站导航:
 
<2014年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜