try块catch块finally块中含有return 问题

尝试注释try、catch 、finally 中的代码,查看运行的结果,如果会debug更好,加深代码的理解

	try {
		//可能抛出异常的代码
     }catch() {           //括号内异常信息
			
        //捕获异常,处理异常的代码
    }finally{
        // 有无异常都执行  (特殊条件下不执行)
    }


知识点

  • return 代表正常退出 返回到上一级调用 ; throw 代表 异常退出,由异常级制动态处理

  • Java 默认异常处理机制 输出异常栈信息并退出程序 ,异常点后程序不会执行

  • 上层异常 由底层异常决定 ----------// 函数是否捕获异常 ----(否)-----主函数是否捕获异常—(否)—默认异常处理机制

  • catch可以有多个,但 不是必需的,异常会自动向上传递

代码

含有return

在这里插入图片描述

public class CloseSource {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int i =test();
		System.out.println(i);
	}
	
/**
 * try块、catch块 中含有return 语句 ,执行return 语句后,不会结束方法,寻找是否含有finally块
 * 没有finally块,方法终止,返回返回值
 * 有finally块,finally块内无return语句,   执行finally块,跳回上述return语句并执行,结束方法
 * 有finally块,finally块内有return语句,   执行finally块中的return语句,结束方法,不会跳到try块、catch块中
 *
 *try块finally块,  finally 里的return语句、抛出的异常 会覆盖try块里的return语句和异常
 * @return
 */
	@SuppressWarnings("finally")
	public static int test() {
		int count=0;
		try {
			System.out.println("try被执行了");
			return count+2;
		}catch(Exception e) {
			System.out.println("catch被执行了");
			return count+5;
		}
		finally {
			System.out.println("finally被执行了");
			return count+10;
		}
	}

}

含有throw
public class CloseSource {

	public static void main(String[] args) throws Exception {
		test();
	}
	
/**
 * try/catch/finally  异常栈信息都会被输出
 * 
 * try/finally    (将catch代码注释掉)   finally 异常会抛出,覆盖try内的异常
 * 
 */
	
	@SuppressWarnings("finally")
	public static int test() throws Exception {
		try {
			System.out.println("try被执行了");
			return 0/0;
			
		}catch(Exception e) {
			System.out.println("catch被执行了");
			e.printStackTrace();
		}
		finally {
			System.out.println("finally被执行了");
			throw new Exception("hello,会覆盖?");
		}
	}

}


如有错误,还望指出

发布了41 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42259578/article/details/91355406
今日推荐