异常处理之finally块的注意事项

1.在finally块中,关闭资源

public class Test{
	public static void main(String[]args){
	
		FileInputStream fis=null;
		FileOutputStream fos=null;
		......
		try{
			
			//do something...
	
	
		}finally{
			//有危险的关闭方式1
			fis.close();
			fos.close();
			
			//有危险的关闭方式2
			if(fis!=null){
				fis.close;
			}
			if(fos!=null){
				fos.close();
			}
			
			//推荐的方式
			if(fis!=null){
				try{
					fis.close();
				}catch(Exception){
					e.printStackTrace();
				}
			}
			if(fos!=null){
				try{
					fos.close();
				}catch(Exception){
					e.printStackTrace();
				}
			}
		}
	}
}

2.finally块的陷阱
 
 public class Test{
 	public static void main(String[]args){
 		FileOutputStream fos=null;
 		try{
 			 // do something...
 			System.out.println("打开资源");
 			System.exit(0);
 		}finally{
 			if(fos!=null){
				try{
					fos.close();
				}catch(Exception){
					e.printStackTrace();
				}
			}
			System.out.println("关闭资源");
 		}
 	}
 }
 
 解释:这个程序"关闭资源"不会输出,因为try块中的System.exit(0);将当前线程停止了,而finally块不能执行已经停止的线程.
 若非要输出“关闭资源”,且执行System.exit(0);则修改如下:
 
public class Test {

	public static void main(String[] args) throws Exception {
		final FileOutputStream fos;
		fos = new FileOutputStream("a.bin");
		System.out.println("打开物理资源");
	
		//为系统注册关闭钩子
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				if (fos != null) {
					try {
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				System.out.println("程序关闭了资源");
			}
		});
		System.out.println("退出程序");
		System.exit(0);
	}
}


3.finally块和方法返回值

public class Test {

	public static void main(String[] args) {
		int a = test();
		System.out.println(a);
	}
	private static int test() {
		int count = 5;
		try {
			System.out.println("try");
			return count + 2; // 不执行
		} finally {
			System.out.println("finally");
			return -1; // 执行
		}
	}
}

解释:当在try块中有return 语句的时候,且有finlly的时候,不会立马执行try块中的return ,而是执行finally中的程序。
若finally块中也有return 语句,则执行finally中的reutrn 语句,然后程序结束,不会执行try块中的return

public class Test {

	public static void main(String[] args) {
		int a = test();
		System.out.println(a);
	}

	private static int test() {
		int count = 5;
		try {
			throw new RuntimeException("测试异常");  //不执行
		} finally {
			System.out.println("finally"); 
			return count;
		}
	}
}

解释:当在try块中抛出异常时候,若finally块中有 return语句,则程序不会真正抛出异常,而是直接执行完finally块后,返回return语句。

 

你可能感兴趣的:(异常处理,JavaSE,finally)