黑马程序员技术交流社区
标题:
return是在finally执行后才返回的
[打印本页]
作者:
@小白@
时间:
2013-7-3 13:19
标题:
return是在finally执行后才返回的
写一个类证明return是在finally执行后才返回的,
//且在finally无法改变返回值。
package com.itheima;
class test06 {
public static int demo() {
int a = 2;
try {
System.out.println("try的 a:" + a);
return a;// 需要被检测的代码块
}
finally // 一定会执行的语句
{
a = 9;
System.out.println("finally的 a:" + a);
}
return a;
}
public static void main(String[] args) {
System.out.println("demo:" + demo());// 调用demo,如果打印结果为1证明
// finally不能改变try里面的返回值
}
}
运行没有结果,这是为啥
作者:
小石头39910
时间:
2013-7-3 13:28
我把代码改了一下,你看看吧
<p>package mypakage;</p><p>//写一个类证明return是在finally执行后才返回的,
//且在finally无法改变返回值。
class Test06 {
public static int demo() {
int a = 2;
try {
System.out.println("try的 a:" + a);</p><p> //return a;// 需要被检测的代码块
}
</p><p> finally // 一定会执行的语句
{
a = 9;
System.out.println("finally的 a:" + a);
}
return a;
}</p><p> public static void main(String[] args) {
System.out.println("demo:" + demo());// 调用demo,如果打印结果为1证明
// finally不能改变try里面的返回值
}
}</p><p>
</p><p> </p>
复制代码
作者:
xuluheng718
时间:
2013-7-3 13:43
本帖最后由 xuluheng718 于 2013-7-3 13:46 编辑
你这完全就不能编译通过,愿意如下:
class test06 {
public static int demo() {
int a = 2;
try {
System.out.println("try的 a:" + a);
return a;// 需要被检测的代码块
}
finally // 一定会执行的语句
{
a = 9;
System.out.println("finally的 a:" + a);
}
return a;
-----------→这句完全就不能被执行,因为try代码块中已经有return了,①没异常则执行完finaly代码块后被try代码块中return了,②假如有异常则finaly代码块执行完毕后这句根本就不会被执行程序就停止了,把这句删了就可以执行了
}
public static void main(String[] args) {
System.out.println("demo:" + demo());// 调用demo,如果打印结果为1证明
// finally不能改变try里面的返回值
}
}
作者:
王洪波
时间:
2013-7-3 13:44
我把原因注释到代码里了,你看下
class test06 {
public static int demo() {
int a = 2;
try {
System.out.println("try的 a:" + a);
return a;// 需要被检测的代码块;这条语句的执行在finally{}语句块的后边
}
finally // 一定会执行的语句
{
a = 9;
System.out.println("finally的 a:" + a);
//return a; //如果这里执行了return语句,程序就结束了,不会再执行try{}块中的return语句
//要想得到你要的结果只能将这个return语句注释掉,才能执行到try{}块里边的return语句
}
}
public static void main(String[] args) {
System.out.println("demo:" + demo());// 调用demo,如果打印结果为1证明
// finally不能改变try里面的返回值
}
}
复制代码
作者:
oxf974025918
时间:
2013-7-3 13:45
程序从上往下执行,有两个return所以编译出错。把finally语句块后面那个return a;去掉就会有结果。try会执行,finally也会被执行,由于a是基本数据类型不会改变他的值最后a还是2.
作者:
@小白@
时间:
2013-7-3 13:51
xiexie ,我明白了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2