有次面试面试官问了这样个问题:有异常时,向上抛出和用try catch有啥区别?
我心想:这平时不是想用哪种就用哪种嘛,还有区别?m d大意了。。。。虽然是个小问题,但说明平时缺少思考,只想着把活干完就完事。其实很多东西都是要平时积累来的,面试临时抱佛脚会漏掉很多细节。于是后面就研究了下,免得下次有人遇到同样的坑。
大致区别就是:
- try..catch捕捉异常后,后续语句会会照常进行
- 向上抛异常到最上层,最上层也往上抛、不处理就会报错,程序停止运行,后面的代码也不会执行
测试
try..catch
public class ThrowsOrTryCatch {
public static void main(String[] args) {
getResult();
System.out.println("1234");
}
public static void getResult() {
try {
new FileInputStream("C:\Gam\123.txt");
} catch (FileNotFoundException e) {
System.out.println("糟糕,有异常:" + e);
}
}
}
运行结果:
可以看到后面的代码System.out.println("1234")有执行
向上抛
public class ThrowsOrTryCatch {
public static void main(String[] args) throws FileNotFoundException {
getResult();
System.out.println("1234");
}
public static void getResult() throws FileNotFoundException {
new FileInputStream("C:\Gam\123.txt");
}
}
运行结果:
这时,后面的代码System.out.println("1234")并没有执行