注意事项
- finally和try相对应,每次try结束后都会调用相对应的finally。(除非直接System.exit()这样不会调用finally)
private static int count=0;
private static void testFinally(){
while(true){
try{
if(count++ == 0)
throw new Exception();
System.out.println("No exception");
}catch(Exception t){
System.out.println("Exception");
}finally{//finally和try相对应,每次try结束后都会调用finally
System.out.println("In finally clause");
if(count == 2) break;
}
}
/*
* 输出:
* Exception
In finally clause
No exception
In finally clause
* */
}
private static void testSystemExit(){
FileInputStream s = null;
try
{
s = new FileInputStream("a.txt");
}
catch(IOException o)
{
System.out.println(o.getMessage());
return ;//finally中的语句会执行
// System.exit(0); // finally中的语句不会执行
}
finally
{
if (s != null)
{
try
{
s.close();
}
catch(IOException oo)
{
oo.printStackTrace();
}
}
System.out.println("执行了finally来回收系统的资源");
}
}
异常丢失
- 在finally中return和抛出异常,都可能导致之前的异常丢失。java中一个方法只能抛出一个异常。
https://blog.csdn.net/ECH00O00/article/details/76474825
https://www.cnblogs.com/wzhanke/p/4778654.html
private static void throwInFinally() {
try{
int num=1/0;
}catch (Exception e){
System.out.println("catch");
throw e;
}finally {
//如果在finally中抛出异常,可能隐藏catch中抛出的异常
//一般finally中有异常都进行日志记录,不影响主要逻辑的运行
throw new OutOfMemoryError();
}
}
private static int returnInFinally() {
try{
int num=1/0;
return num;
}catch (Exception e){
System.out.println("catch");
throw new Exception();
}finally {
//如果在finally中return,可能隐藏catch中抛出的异常,异常被吃掉。等同于告诉程序没有异常
return 1;
}
}
private static int returnInFinally1() {
try{
return 2;
}finally {
return 1;//最终返回的1,将2覆盖
}
}