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";  
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值