java面试系列--J2SE基础(三)

本文主要探讨了Java中try-catch-finally语句块的执行逻辑,即使try或catch中有return,finally块仍然会执行。此外,详细介绍了Exception与Error的区别,并列举了四种不同类型的内存溢出错误:Java堆溢出、虚拟机栈和本地方法栈溢出、运行时常量池溢出以及方法区溢出,分析了它们的触发条件和解决策略。
摘要由CSDN通过智能技术生成

14. try catchfinally,try里有return,finally还执行么?

1)、不管是否出现异常,finally块中代码都会执行;

2)、当try和catch中有return时,finally仍然会执行;

3)、finally是在return后面的表达式运算后执行的,具体返回哪一个,看下面的例子,不建议在finally里return,一般finally用于比如关闭资源等;

package com.ws.test;

/**
 * @author WeiS
 *
 */
public class MyDemo {

	public static void main(String[] args) {
		System.err.println(exceptionTest());
		System.err.println(exceptionTest1());
		System.err.println(exceptionTest2());
	}

	private static int exceptionTest() {
		int a = 0;
		try {
			a = 1;
			throw new RuntimeException("this is my exception");
		} catch (Exception e) {
			return a;
		}finally {
			a = 3;
			return a;
		}
	}
	
	private static String exceptionTest1() {
		try {
			throw new RuntimeException("this is my exception");
		} catch (Exception e) {
			return "abc";
		}finally {
			return "efd";
		}
	}
	
	private static String exceptionTest2() {
		try {
			return "abc";
			//throw new RuntimeException("this is my exception");
		} catch (Exception e) {
			return "abcdef";
		}finally {
			return "efd";
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值