java - try-catch-finally 后返回

标签 java return try-catch try-catch-finally finally

我知道 try、catch 和 finally 是如何工作的(大部分情况下),但我有一件我想知道的事情:在 try-catch-finally 之后的 return 语句会发生什么,而我们已经在 try 中有一个 return (或捕获)?

例如:

public boolean someMethod(){
    boolean finished = false;
    try{
        // do something
        return true;
    }
    catch(someException e){
        // do something
    }
    finally{
        // do something
    }
    return finished;
}

假设尝试没有出错,所以我们返回 true。然后我们会去 finally 我们做一些像关闭一个连接的事情,然后呢?

我们在finally中做了一些事情之后方法会停止(所以方法在try中返回true),还是在finally之后方法继续,导致返回finished(即假)?

提前感谢您的回复。

最佳答案

finally block 被执行的事实不会让程序忘记你返回。如果一切顺利,finally block 之后的代码就不会被执行。

这是一个清楚的例子:

public class Main {

    public static void main(String[] args) {
        System.out.println("Normal: " + testNormal());
        System.out.println("Exception: " + testException());
    }

    public static int testNormal() {
        try {
            // no exception
            return 0;
        } catch (Exception e) {
            System.out.println("[normal] Exception caught");
        } finally {
            System.out.println("[normal] Finally");
        }
        System.out.println("[normal] Rest of code");
        return -1;
    }

    public static int testException() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.out.println("[except] Exception caught");
        } finally {
            System.out.println("[except] Finally");
        }
        System.out.println("[except] Rest of code");
        return -1;
    }

}

输出:

[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1

关于java - try-catch-finally 后返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533128/

相关文章:

java - 简化java中的方法设计

java - 使用 AOP 的 Spring session 范围 bean 中的问题

java - 如何 jsonify 具有新值的对象?

C: 函数可以返回一个全局变量吗?

nested - 如何在Swift 2.0中处理连续多次尝试

sql - 如何在 vb.net 中使用 try 和 catch block ?

java - 使用 Test Fairy 插件上传 APK 问题

swift - void 函数中意外的非 void 返回值 - Swift

android - 无法覆盖 AsyncTask 类中的 onPostExecute() 方法

javascript - Node.js MySQL 查询中的 Try/Catch 是冗余的吗?