In Java, will the code in the finally block be called and run after a return statement is executed?

The answer to this question is a simple yes – the code in a finally block will take precedence over the return statement. Take a look at the code below to confirm this fact:

Code that shows finally runs after return

class SomeClass
{
    public static void main(String args[])
    {
        // call the proveIt method and print the return value
    	System.out.println(SomeClass.proveIt());
    }

    public static int proveIt()
    {
    	try {
            	return 1;
    	}
    	finally {
    	    System.out.println("finally block is run
            before method returns.");
    	}
    }
}

  

Running the code above gives us this output:

finally block is run before method returns.
1

  

From the output above, you can see that the finally block is executed before control is returned to the “System.out.println(SomeClass.proveIt());” statement – which is why the “1” is output after the “finally block is run before method returns.” text.

Very unique situations when finally will not run after return

The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.

What if there is a return statement in the finally block as well?

If you have a return statement in both the finally block and the try block, then you could be in for a surprise. Anything that is returned in the finally block will actuallyoverride any exception or returned value that is inside the try/catch block. Here is an example that will help clarify what we are talking about:

public static int getANumber(){
    try{
        return 7;
    } finally {
        return 43;
    }
}

  

The code above will actually return the “43” instead of the “7”, because the return value in the finally block (“43″) will override the return value in the try block (“7″).

Also, if the finally block returns a value, it will override any exception thrown in the try/catch block. Here is an example:

public static int getANumber(){
    try{
        throw new NoSuchFieldException();
    } finally {
        return 43;
    }
}

  

A return statement in the finally block is a bad idea

Running the method above will return a “43” and the exception in the try block will not be thrown. This is why it is considered to be a very bad idea to have a return statement inside the finally block.

时间: 2024-11-07 16:06:54

In Java, will the code in the finally block be called and run after a return statement is executed?的相关文章

【Java】Unreachable code编译异常

如下代码在Java中是不可以编译的: public class unReachableTest { public static void main(String[] args) { while(true){ } System.out.println("aaaaaa"); } } 这段代码的看起来没有任何语法错误,但是非常明显可以知道,这段代码根本就没有意思,aaaaa永远都不会输出, 然而,Java不同于C语言,Java认为这段代码是存在一个不可达的语言错误,根本就不可以编译. 如果你

java post request code

/* * Project Name:Tconfig * File Name:Main.java * Package Name:packages * Date:2017-3-21下午6:03:01 * Copyright (c) 2017, [email protected] 陈飞 Rights Reserved. * */ package packages; import java.io.BufferedReader; import java.io.IOException; import jav

java 多线程系列基础篇(三)之start()和run()的区别

概要 Thread类包含start()和run()方法,它们的区别是什么?本章将对此作出解答. start() 和 run()的区别说明 start() : 它的作用是启动一个新线程,新线程会执行相应的run()方法.start()不能被重复调用.run()   : run()就和普通的成员方法一样,可以被重复调用.单独调用run()的话,会在当前线程中执行run(),而并不会启动新线程! 下面以代码来进行说明. class MyThread extends Thread{ public voi

Java Code Examples for io.netty.util.concurrent.GlobalEventExecutor

Example 1 Project: lettuce   File: FuturesTest.java View source code 6 votes @Test public void regularUse() throws Exception { final DefaultPromise<Boolean> target = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE); Futures.PromiseAgg

Java 并发工具包 java.util.concurrent 大全

1. java.util.concurrent - Java 并发工具包 Java 5 添加了一个新的包到 Java 平台,java.util.concurrent 包.这个包包含有一系列能够让 Java 的并发编程变得更加简单轻松的类.在这个包被添加以前,你需要自己去动手实现自己的相关工具类. 本文我将带你一一认识 java.util.concurrent 包里的这些类,然后你可以尝试着如何在项目中使用它们.本文中我将使用 Java 6 版本,我不确定这和 Java 5 版本里的是否有一些差异

Java Web基础知识 2

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page import="java.util.*"%> 4 <%@ page import="java.sql.*" %> 5 <%@ page errorPage=&quo

Java_并发工具包 java.util.concurrent 用户指南(转)

译序 本指南根据 Jakob Jenkov 最新博客翻译,请随时关注博客更新:http://tutorials.jenkov.com/java-util-concurrent/index.html.本指南已做成中英文对照阅读版的 pdf 文档,有兴趣的朋友可以去 Java并发工具包java.util.concurrent用户指南中英文对照阅读版.pdf[带书签] 进行下载. 1. java.util.concurrent - Java 并发工具包 Java 5 添加了一个新的包到 Java 平台

Java Web基础知识 1

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page import="java.util.*"%> 4 <%@ page import="java.sql.*" %> 5 <%@ page errorPage=&quo

javaCore分析示例(转)

当两个或多个线程彼此形成循环依赖关系时,就出现了死锁.例如,如果线程 A 处于等待线程 B 的等待状态,而同时线程 B 处于等待线程 A 的等待状态,则出现了死锁.一旦形成此情况,线程 A 和线程 B 都不能有任何进展,因为这两个线程现在都无限期地挂起了.为什么会有人创建这种系统?当然,您并不会有意这么做,但由于存在大量线程和复杂事务,因此很容易出现这种情况. 本文将介绍如何使用 IBM WebSphere Application Server V6.1 的线程转储工具来对系统进行检查,以确定是