欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java,

来源: javaer 分享于  点击 23467 次 点评:25

Java,


有点困惑了,try...catch...finally

 

我们在知道:finally不论在什么情况下都会执行。面对下面的代码,我有点困惑了,大家如果知道原因,指导指导。

 

public static void main(String[] args) {
		
		System.out.println("Hello World!");
		
		System.out.println(getValues());	
		
	}	
	
	
	private static int getValues(){
		int value = -1;
		try {
			value = 10 ;
			System.out.println(" value current1 in try is " + value);
			return value;
		} catch (Exception e) {
			value = 0 ;
			return value;
		}finally{
			value = 5 ;
			System.out.println(" value current2 in finally is " + value);
			
		}
	}

 

返回结果:

写道 Hello World!
value current1 in try is 10
value current2 in finally is 5
10

 

 

疑问

      在finally中改变了value的值,为什么返回的值还是10???

 

如果在finally中也加上“return value;”,则返回结果如下:

写道 Hello World!
value current1 in try is 10
value current2 in finally is 5
5

 

如果将getValue方法修改如下:

	private static int getValues(){
		int value = -1;
		try {
			value = 10 ;
			System.out.println(" value current1 in try is " + value);
		} catch (Exception e) {
			value = 0 ;
		}finally{
			value = 5 ;
			System.out.println(" value current2 in finally is " + value);			
		}	
		System.out.println(" value current2 in getValues is " + value);
		return value;
	}
 


返回结果如下:

写道 Hello World!
value current1 in try is 10
value current2 in finally is 5
value current2 in getValues is 5
5
 

所以对于这个疑问,我无解了!!!

 

 

大哥大姐帮个忙解答解答!!!

 

 

 

 

 

相关文章

    暂无相关文章
相关栏目:

用户点评