Java异常机制---三个关键字try catch finally

1. 异常关键字---try catch finally 

public abstract class TryCatchFinally {
/**
 * 异常处理方法之一,捕获异常
 * try  catch  finally
 * try:可能出现异常的逻辑语句,一旦出现异常则停止程序运行,异常被捕获
 * catch:出现异常,捕获,抛出异常,需要处理
 * finally:总会被执行,放置关闭资源的代码,节约内存
 */
	public static void main(String[] args) {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			System.out.println("finally内的程序总会被执行,用于释放缓存,节省内存");
		}
	}
}

2. try catch finally return 的执行顺序

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * try catch finally return 的执行顺序
 * {1.执行 try catch 给返回值赋值
 *  2.执行finally
 *  3.返回值}
 *  finally中不能使用return 否则只会返回finally内的返回值,原来的返回值被覆盖
 * @author Administrator
 *
 */
public class TestException03 {
	public static void main(String[] args) {
		String str = new TestException03().openFile();
		System.out.println(str);
	}
	
	String openFile(){
		System.out.println("aaa");
		try {
			FileInputStream fis = new FileInputStream("E:/new folder/a.txt");
			int a = fis.read();
			System.out.println("bbb");
			return "step1";
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("catching");
			e.printStackTrace();
			return "step2";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "step3";
		}finally{
			System.out.println("finally");
	//		return "fff";  
		}
	}
}


猜你喜欢

转载自blog.csdn.net/qq_30007589/article/details/80851219