java try两个,在java中,如果两个try和catch都抛出相同的异常,最后有没有返回?...

public class Abc {

public static void main(String args[]) {

System.out.println(Abc.method());

}

static int method() {

try {

throw new Exception();

}

catch(Exception e) {

throw new Exception();

}

finally {

return 4;

}

}

}

Why is the return value 4?

解决方案

That's the way finally works. The snippet

try {

throw new Exception();

} catch(Exception e) {

throw new Exception();

}

will complete abruptly, but the finally clause will kick in and when it returns it discards the original reason for completing the statement.

This is explained in section Blocks and Statements in the Java Language Specification. I've highlighted the relevant path in your situation:

A try statement with a

finally block is executed

by first executing the

try block. Then there is

a choice:

If

execution of the try

block completes normally, then the

finally block is

executed, and then there is a choice:

...

If execution

of the try block

completes abruptly because of a

throw of a value

V, then there is a choice:

If

the run-time type of V is

assignable to the parameter of any

catch clause of the

try statement, then the

first (leftmost) such

catch clause is selected.

The value V is assigned to the

parameter of the selected

catch clause, and the

Block of that

catch clause is executed.

Then there is a choice:

If the

catch block completes

normally, then the

finally block is

executed. Then there is a choice: ...

If the

catch block completes

abruptly for reason R, then the

finally block is

executed. Then there is a choice:

If the

finally block completes

normally, then the try

statement completes abruptly for

reason R.

If the finally

block completes abruptly for reason

S, then the try

statement completes abruptly for

reason S (and reason R

is discarded).

If the run-time type of V

is not assignable to the parameter of

any catch clause of the

try statement, then the

finally block is

executed. Then there is a choice: ...

If execution of the

try block completes

abruptly for any other reason

R, then the

finally block is

executed. Then there is a choice: ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值