有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

若catch语句返回,那个么为什么它最终会阻塞呢?

package com.ami.practice;
public class UnrechebleStatement {
public static void main(String[] args) {
    System.out.println(m());
        }

public static int m(){
    try{
        int x=0;
        int y=10/x;
        return y;
    }catch(Exception e){
        return 1;
    }finally {
        return 2;
    }
  }
}

共 (3) 个答案

  1. # 1 楼答案

    来自JLS#14.17

    A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.

    [...]

    The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the method or constructor whose try blocks or catch clauses contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

    特别是第二部分应该完美地回答你的问题

  2. # 2 楼答案

    最后,块总是被执行。。。无论是执行审判还是捕获

  3. # 3 楼答案

    除了在某些情况下,Finally总是被调用
    1) 如果是系统。exit()被调用
    2) 如果jvm崩溃
    3) 如果我们使用嵌套的try catch