开发者

Unreachable statement when using return in finally?

This compiles:

class Ex1 {
    public int show() {
        try {
            int a=10/10;
            return 10;
        }   
        catch(ArithmeticException e) {
            System.out.println(开发者_运维问答e);
        }
        finally {
            System.out.println("Finally");
        }
        System.out.println("hello");
        return 20;
    }
}

on the other hand this doesn't:

class Ex15 {
    public int show() {
        try {
            int a=10/0;
            return 10;
        }
        catch(ArithmeticException e) {
            System.out.println(e);
        }
        finally {
            System.out.println("Finally");
            return 40;
        }

        System.out.println("hello");
        return 20;
    }
}

and gives unreachable statement System.out.println("hello"); error. why is it so?


The finally has a return so you are probably getting an unreachable code block error.

finally
{   
    System.out.println("Finally"); 
    return 40;
}
System.out.println("hello"); // unreachable code
return 20;

This is actually a compile-time error in Java. See section 14.20.

It is a compile-time error if a statement cannot be executed because it is unreachable.


It's unreachable code. According to the compiler, System.out.println("hello"); can never be executed.

Beside that, DON'T EVER write return within a finally block. (see Hidden Features of Java for why you should not).

EDIT:

Yes, but what makes return in finally do this?

It's not because it is in a finally block or something. Even if you'd remove the finally keyword, you will still get the error.

   class ex15 {
        public int show() {
            int a = 10 / 0;
            return 40;
            System.out.println("hello");
            return 20;
        }
    }

Obviously, if you return 40, there is no way you can execute the next line. finally just means "do always, no matter what". So.


When you put a "return" in the "finally" block, anything that comes after it will never be executed. The "return" statement ends the method right there.

You would get the same error if you put a System.out.println() in the first method, after the "return" statement in it.


You have a return in the finally block. This makes any statements after that unreachable. Also you have a return in the try block and again in the finally block. This doesn't make sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜