`
joknm
  • 浏览: 61925 次
  • 性别: Icon_minigender_1
  • 来自: 南宁
社区版块
存档分类
最新评论

finally 浅谈

    博客分类:
  • JAVA
 
阅读更多
近日做程序时突发奇想:try ... finally ... 中的 finally 会在返回前执行(在XXX书上看到的,忘了书名了),是于做了以下测试
public class FinallyTest 
{
	public static void main(String args[])
	{
		System.out.println("return: " + new FinallyTest().getString());
	}
	
	public String getString()
	{
		String returnString = null;
		try
		{
			returnString = "this string will be return.";
			return returnString;		
		}finally
		{			
			System.out.println("execute finally...");
			System.out.println("before clean returnString's value: " + returnString);
			returnString = null;
			System.out.println("after  clean returnString's value: " + returnString);
			System.out.println("execute finally end.");
		}		
	}
}

测试结题:
execute finally...
before clean returnString's value: this string will be return.
after  clean returnString's value: null
execute finally end.
return: this string will be return.

如果返回前执行,那么返回的字符串应该为空。但从结果来看,似乎出人的意料之外。
考虑原因:返回前将返回的结果拷贝了。

于是做了以下修改:
public class FinallyTest 
{
	public static void main(String args[])
	{
		System.out.println("return: " + new FinallyTest().getMessage().message);
	}
	
	public Message getMessage()
	{
		Message returnMessage = new Message();
		try
		{
			returnMessage.message = "message";
			return returnMessage;		
		}finally
		{			
			System.out.println("execute finally...");
			System.out.println("before clean returnString's value: " + returnMessage.message);
			returnMessage.message = null;
			System.out.println("after  clean returnString's value: " + returnMessage.message);
			System.out.println("execute finally end.");
		}		
	}
}

class Message
{
	public String message = "message";
}


结果:
execute finally...
before clean returnString's value: message
after  clean returnString's value: null
execute finally end.
return: null

从结果来看,只调用了对象的引用,而对象没有被拷贝。
看来,如所下用 finally 统一处理一般数据类型还是免谈了。
public class FinallyTest 
{
	public static void main(String args[])
	{
		System.out.println("return: " + new FinallyTest().getInt());
	}
	
	public int getInt()
	{
		int returnInt = 0;
		try
		{
			returnInt = 1;
			throw new RuntimeException("...");
		}catch(Exception e)
		{
			returnInt = 2;
			return returnInt;
		}finally
		{			
			System.out.println("execute finally...");
			System.out.println("before switch returnInt's value: " + returnInt);
			switch(returnInt)
			{
				case 1:
					returnInt = 0;
					break;
				case 2:
					returnInt = 3;
					break;
				default:
					returnInt = 4;
			}
			System.out.println("after  switch returnInt's value: " + returnInt);
			System.out.println("execute finally end.");
		}		
	}
}
分享到:
评论
41 楼 ghy_20081010 2011-01-05  
String 是常量 重新赋值意味着创建新对象 finally 与 return 不是同一对象引用地址。 用类封装则不同。
40 楼 zhangkaitao 2011-01-03  
   public class FinallyTest   
   {  
       public static void main(String args[])  
        {  
            System.out.println("return: " + new FinallyTest().getString());  
        }  
          
        public String getString()  
        {  
           String returnString = null;  
           try  
           {  
               returnString = "this string will be return.";  
               return returnString;          
           }finally  
           {             
               System.out.println("execute finally...");  
               System.out.println("before clean returnString's value: " + returnString);  
               returnString = null;  
              System.out.println("after  clean returnString's value: " + returnString);  
              System.out.println("execute finally end.");  
          }         
      }  
  }  


  今天又看这段代码,想起来问什么了?String是不可变类型,比如"a" + "b" 会生成一个新的对象,
  如
String a = “1”;
b = a;

会如何呢?复制,肯定是复制,即首先复制a的值,然后放如b是不?
因此return也是同样道理,首先把“returnString”的值复制出来是不,然后return回去。

 
39 楼 anhaoy 2010-07-30  
Danteng 里面 无限递归了,必然有   StackOverflowError
但是 就算出 StackOverflowError ,也还是要执行 finally ,所有 还是 有很多很多输出。。。。
38 楼 caohonghui725 2010-07-30  
yangguo,您确定您试过这个代码么?根本跟LZ的结果不一样啊!
37 楼 lianglaiyang 2010-07-30  
这个问题其实可以分成两步来解答:
1、try...finally中变量的关系是跟方法参数传递一样的。
2、方法参数传递只有值传递,没有引用传递。


所以要理解这个问题,就要理解方法中参数是怎么传递,而这个问题之前已有高手写过贴子!
36 楼 IcyFenix 2010-07-30  
hardPass 写道
改成

catch(Throwable e)

也不报StackOverflowError

奶奶的,为啥子?


} catch (Throwable e) {
    flag.set(false);
}

看看你的程序还会不会打印。
35 楼 IcyFenix 2010-07-30  
hardPass 写道

关键是没有看到异常,e.printStackTrace();


= =# 孩子,细心一些。

catch(Exception e) --> catch (Throwable e),我都提示是SOF错了,还放一个exception来抓?

34 楼 fyf_008 2010-07-30  
joknm 写道
我只是想知道一下是不是正的如其它人所说任东西需要后期处理的东西(比如数据链接释放之类的)都可以话到 finally 里面去处理。





请务必相信我的,我这个才是正确的,不关你看了什么书,

我的这个说法,是 java 作者告诉我的———玩笑玩笑。。

33 楼 zhaohaiyang 2010-07-30  
这问题其实比较无聊,楼主估计一时蛋疼
32 楼 hardPass 2010-07-30  
改成

catch(Throwable e)

也不报StackOverflowError

奶奶的,为啥子?
31 楼 hardPass 2010-07-30  
IcyFenix 写道
hardPass 写道

下面的程序打印出第一次执行"finally"的深度
打印出来的值是5761、5730、5515,每次结果还都不一样

但是,我觉得,不应该执行finally,因为try还没有执行完,danteng......

public static void main(String[] args) {
		doSomething();
	}
	
	static AtomicBoolean flag = new AtomicBoolean(true);
	static AtomicInteger count = new AtomicInteger(0);
	static void doSomething() {
		//int x = count.get();
		//if(x>100)
		//	return;
		count.incrementAndGet();

		try {
			//System.out.println("try..." + x);
			doSomething();
		}catch(Exception e){
			e.printStackTrace();
		}
		finally {
			if(flag.get()){
			System.out.println("finally" + count.get());
			flag.set(false);
			return;
			}
			
			doSomething();
		}
	}




别蛋疼了,退出不一定要return,抛异常而已可以。这里有StackOverflowError出现,finally当然会执行。


关键是没有看到异常,e.printStackTrace();
30 楼 IcyFenix 2010-07-30  
hardPass 写道

下面的程序打印出第一次执行"finally"的深度
打印出来的值是5761、5730、5515,每次结果还都不一样

但是,我觉得,不应该执行finally,因为try还没有执行完,danteng......

public static void main(String[] args) {
		doSomething();
	}
	
	static AtomicBoolean flag = new AtomicBoolean(true);
	static AtomicInteger count = new AtomicInteger(0);
	static void doSomething() {
		//int x = count.get();
		//if(x>100)
		//	return;
		count.incrementAndGet();

		try {
			//System.out.println("try..." + x);
			doSomething();
		}catch(Exception e){
			e.printStackTrace();
		}
		finally {
			if(flag.get()){
			System.out.println("finally" + count.get());
			flag.set(false);
			return;
			}
			
			doSomething();
		}
	}




别蛋疼了,退出不一定要return,抛异常而已可以。这里有StackOverflowError出现,finally当然会执行。
29 楼 zhangkaitao 2010-07-30  
我觉得这是jdk设计者故意设计的,finally 是在try 和 catch 返回之前做,但返回的值已经被提前保存了,所以会出现这种情况,这就说明jdk是传值而非引用,如果是引用就不会有这个问题。
28 楼 drift_ice 2010-07-30  
joknm 写道
drift_ice 写道
public class T{
    public int test(){
        int a=0;
        try{
            return a;
        }finally{
            a++;
        }
        
    }
    
    public static void main(String[] args){
        T t=new T();
        System.out.println(t.test());
    }
}


其中方法test的字节码如下:

public int test();
  Code:
   0:   iconst_0     #0,1:对应int a=0;
   1:   istore_1
   2:   iload_1      #2,3:对应int result=a;
   3:   istore_2
   4:   iinc    1, 1 #4:对应a++
   7:   iload_2      #7,8:对应return result
   8:   ireturn
   9:   astore_3     #9:对应Exception e
   10:  iinc    1, 1 #10:对应a++
   13:  aload_3      #13:,14:对应throw e
   14:  athrow
  Exception table:
   from   to  target type
     2     4     9   any
     9    10     9   any


首先,明确finally干了什么事?
其实class里并没有直接支持finally的机制,编译时finally中的内容会出现在两处地址(以上4行和10行),第一处是在执行try-catch中的代码后,第二次是出现在出现异常时。

其次,怎么返回值
如上2-8行所述,首先是将要返回的值保存在另一个本地变量的位置(istore_2),注意,这个跟a的变量位置1是不同的位置,相当于会先保存需要要返回基本类型的值或者对象的引用到某个变量中,然后再返回这个变量。

结论:所以返回时a的值确实是1,但是返回的并不是a,而是编译器为我们设置隐藏的变量result,其值为0

同理,如果是返回对象,如
public class T{
    public A test(){
        A a=new A();
        try{
            return a;
        }finally{
            a.i++;
        }
        
    }
    
    public static void main(String[] args){
        T t=new T();
        System.out.println(t.test().i);
    }
    
    static class A{
        public int i=0;
    }
}


不妨猜猜会返回多少


听君分析豁然开朗。
请教下以下的是用什么来查看的?
public int test();
  Code:
   0:   iconst_0     #0,1:对应int a=0;
   1:   istore_1
   2:   iload_1      #2,3:对应int result=a;
   3:   istore_2
   4:   iinc    1, 1 #4:对应a++
   7:   iload_2      #7,8:对应return result
   8:   ireturn
   9:   astore_3     #9:对应Exception e
   10:  iinc    1, 1 #10:对应a++
   13:  aload_3      #13:,14:对应throw e
   14:  athrow
  Exception table:
   from   to  target type
     2     4     9   any
     9    10     9   any



javap -c xxx
27 楼 joknm 2010-07-30  
drift_ice 写道
public class T{
    public int test(){
        int a=0;
        try{
            return a;
        }finally{
            a++;
        }
        
    }
    
    public static void main(String[] args){
        T t=new T();
        System.out.println(t.test());
    }
}


其中方法test的字节码如下:

public int test();
  Code:
   0:   iconst_0     #0,1:对应int a=0;
   1:   istore_1
   2:   iload_1      #2,3:对应int result=a;
   3:   istore_2
   4:   iinc    1, 1 #4:对应a++
   7:   iload_2      #7,8:对应return result
   8:   ireturn
   9:   astore_3     #9:对应Exception e
   10:  iinc    1, 1 #10:对应a++
   13:  aload_3      #13:,14:对应throw e
   14:  athrow
  Exception table:
   from   to  target type
     2     4     9   any
     9    10     9   any


首先,明确finally干了什么事?
其实class里并没有直接支持finally的机制,编译时finally中的内容会出现在两处地址(以上4行和10行),第一处是在执行try-catch中的代码后,第二次是出现在出现异常时。

其次,怎么返回值
如上2-8行所述,首先是将要返回的值保存在另一个本地变量的位置(istore_2),注意,这个跟a的变量位置1是不同的位置,相当于会先保存需要要返回基本类型的值或者对象的引用到某个变量中,然后再返回这个变量。

结论:所以返回时a的值确实是1,但是返回的并不是a,而是编译器为我们设置隐藏的变量result,其值为0

同理,如果是返回对象,如
public class T{
    public A test(){
        A a=new A();
        try{
            return a;
        }finally{
            a.i++;
        }
        
    }
    
    public static void main(String[] args){
        T t=new T();
        System.out.println(t.test().i);
    }
    
    static class A{
        public int i=0;
    }
}


不妨猜猜会返回多少


听君分析豁然开朗。
请教下以下的是用什么来查看的?
public int test();
  Code:
   0:   iconst_0     #0,1:对应int a=0;
   1:   istore_1
   2:   iload_1      #2,3:对应int result=a;
   3:   istore_2
   4:   iinc    1, 1 #4:对应a++
   7:   iload_2      #7,8:对应return result
   8:   ireturn
   9:   astore_3     #9:对应Exception e
   10:  iinc    1, 1 #10:对应a++
   13:  aload_3      #13:,14:对应throw e
   14:  athrow
  Exception table:
   from   to  target type
     2     4     9   any
     9    10     9   any

26 楼 drift_ice 2010-07-30  
public class T{
    public int test(){
        int a=0;
        try{
            return a;
        }finally{
            a++;
        }
        
    }
    
    public static void main(String[] args){
        T t=new T();
        System.out.println(t.test());
    }
}


其中方法test的字节码如下:

public int test();
  Code:
   0:   iconst_0     #0,1:对应int a=0;
   1:   istore_1
   2:   iload_1      #2,3:对应int result=a;
   3:   istore_2
   4:   iinc    1, 1 #4:对应a++
   7:   iload_2      #7,8:对应return result
   8:   ireturn
   9:   astore_3     #9:对应Exception e
   10:  iinc    1, 1 #10:对应a++
   13:  aload_3      #13:,14:对应throw e
   14:  athrow
  Exception table:
   from   to  target type
     2     4     9   any
     9    10     9   any


首先,明确finally干了什么事?
其实class里并没有直接支持finally的机制,编译时finally中的内容会出现在两处地址(以上4行和10行),第一处是在执行try-catch中的代码后,第二次是出现在出现异常时。

其次,怎么返回值
如上2-8行所述,首先是将要返回的值保存在另一个本地变量的位置(istore_2),注意,这个跟a的变量位置1是不同的位置,相当于会先保存需要要返回基本类型的值或者对象的引用到某个变量中,然后再返回这个变量。

结论:所以返回时a的值确实是1,但是返回的并不是a,而是编译器为我们设置隐藏的变量result,其值为0

同理,如果是返回对象,如
public class T{
    public A test(){
        A a=new A();
        try{
            return a;
        }finally{
            a.i++;
        }
        
    }
    
    public static void main(String[] args){
        T t=new T();
        System.out.println(t.test().i);
    }
    
    static class A{
        public int i=0;
    }
}


不妨猜猜会返回多少
25 楼 joknm 2010-07-30  
我只是想知道一下是不是正的如其它人所说任东西需要后期处理的东西(比如数据链接释放之类的)都可以话到 finally 里面去处理。

fyf_008 写道
楼主回答有些许问题。。

对象绝对没有 Copy. 或者说是克隆。你要用Java,就要知道Java的设计者如何设计java .这问题就解决



那为什么呢,

return obj;

只是 将返回引用(returnPointer),指向了obj 这个引用 指向的对象,

并没有Copy,

虽然,你在 finally 里面,把obj=null;
那只是, obj 这个引用,指向发生了变化,没有影响返回引用(returnPointer)




我原以为基本数据类型是以拷贝的形式传回值的(某些书上说的),现在由你这么说我也不知道谁对谁错了,有机会再去了解一个是怎么个传值回来的。

wujiazhao88 写道
楼主你试下这个程序看看,看看能不能猜到运行结果。

public class Danteng{
public static void main(String[] args){
 doSomething();
}

static void doSomething(){

try{
 System.out.println("try...");
 doSomething();
}finally{
System.out.println("finally");
doSomething();
}
}

}




这个问题确实很是 Danteng 1000多次以前都不会执行 finall ,4000次以后才会执行 finally。 这个问题够蛋疼的。
24 楼 superheizai 2010-07-30  
fyf_008 写道
楼主回答有些许问题。。

对象绝对没有 Copy. 或者说是克隆。你要用Java,就要知道Java的设计者如何设计java .这问题就解决



那为什么呢,

return obj;

只是 将返回引用(returnPointer),指向了obj 这个引用 指向的对象,

并没有Copy,

虽然,你在 finally 里面,把obj=null;
那只是, obj 这个引用,指向发生了变化,没有影响返回引用(returnPointer)



同意。
在执行到return语句的时候,return的其实是obj的地址。你对指向String的obj来说,任何操作改变的只是obj的指向,而不会改变String的内容。而楼主第二个例子,指向的是一般对象,对obj的改变同时也改变了其初始指向地址空间的值。
个人浅见,说错无怪
23 楼 sunliao_first 2010-07-30  
。。。。。
22 楼 hardPass 2010-07-30  

下面的程序打印出第一次执行"finally"的深度
打印出来的值是5761、5730、5515,每次结果还都不一样

但是,我觉得,不应该执行finally,因为try还没有执行完,danteng......

public static void main(String[] args) {
		doSomething();
	}
	
	static AtomicBoolean flag = new AtomicBoolean(true);
	static AtomicInteger count = new AtomicInteger(0);
	static void doSomething() {
		//int x = count.get();
		//if(x>100)
		//	return;
		count.incrementAndGet();

		try {
			//System.out.println("try..." + x);
			doSomething();
		}catch(Exception e){
			e.printStackTrace();
		}
		finally {
			if(flag.get()){
			System.out.println("finally" + count.get());
			flag.set(false);
			return;
			}
			
			doSomething();
		}
	}


相关推荐

    浅谈Java中return和finally的问题

    在Java中当try、finally语句中包含return语句时,执行情况到底是怎样的,finally中的代码是否执行,大家众说纷纭,有的说会执行,有的说不会执行,到底哪种说法正确,下面我们来详细讨论下

    浅谈Java finally语句到底是在return之前还是之后执行(必看篇)

    下面小编就为大家带来一篇浅谈Java finally语句到底是在return之前还是之后执行(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    浅谈软件安全设计(一)

    浅谈软件安全设计(一) code by 黑夜彩虹 & vxin with almost pure delphi 网站:http://soft.eastrise.net 2007-03-07 --- 转载时请保留作者信息。 **************************************...

    浅谈JavaScript异常处理语句

    包含try-catch、try-catch-finally和throw. try-catch语句 try{ tryStatements } catch(exception){ catchStatements } 参数说明: tryStatements:必选项。可能发生错误的语句序列。 exception:必选项。任何变量...

    浅谈javascript 函数表达式和函数声明的区别

    以函数声明的方法定义的函数并不是真正的声明,它们仅仅可以出现在全局中,或者嵌套在其他的函数中,但是它们不能出现在循环,条件或者try/catch/finally中,而  函数表达式可以在任何地方声明. 下面分别用两种方法定义...

    浅谈Python中的异常和JSON读写数据的实现

    异常可以防止出现一些不友好的信息返回给用户,有助于提升程序的可用性,在java中通过try … catch … finally来处理异常,在Python中通过try … except … else来处理异常 一、以ZeroDivisionError为例,处理分母为...

    浅谈C#中简单的异常引发与处理操作

    异常处理使用 try、catch 和 finally 关键字尝试某些操作,以处理失败情况,尽管这些操作有可能失败,但如果您确定需要这样做,且希望在事后清理资源,就可以尝试这样做。公共语言运行时 (CLR)、.NET Framework 或...

    Python核心编程(第二版).pdf (压缩包分2部分,第二部分)

     6.20 *拷贝python对象、浅拷贝和深拷贝   6.21 序列类型小结   6.22 练习   第7章 映像和集合类型   7.1 映射类型:字典   7.1.1 如何创建字典和给字典赋值   7.1.2 如何访问字典中的值   ...

    Python核心编程(第二版).pdf (压缩包分2部分,第一部分)

     6.20 *拷贝python对象、浅拷贝和深拷贝   6.21 序列类型小结   6.22 练习   第7章 映像和集合类型   7.1 映射类型:字典   7.1.1 如何创建字典和给字典赋值   7.1.2 如何访问字典中的值   ...

    Delphi7.完美经典

    6-6-3 浅谈指针与数据结构 6-7 程序与函数(Procedures and Functions) 6-7-1 函数的意义与优点 6-7-2 函数的分类与效用 6-7-3 自定义函数使用方法概述 6-7-4 函数的声明、定义及其实现 6-7-5 参数传递方式 6-...

    Python核心编程第二版(ok)

     6.20 拷贝Python对象.c浅拷贝和深拷贝   6.21 序列类型小结   6.22 练习   第7章 映像和集合类型   7.1 映射类型:字典   7.1.1 如何创建字典和给字典赋值   7.1.2 如何访问字典中的值   ...

    Python核心编程第二版

     6.20 *拷贝Python对象、浅拷贝和深拷贝   6.21 序列类型小结   6.22 练习   第7章 映像和集合类型   7.1 映射类型:字典   7.1.1 如何创建字典和给字典赋值   7.1.2 如何访问字典中的值   ...

    ASP.NET3.5从入门到精通

    2.7.4 try-catch-finally 异常语句 2.8 小结 第 3 章面向对象设计基础 3.1 什么是面向对象 3.1.1 传统的面向过程 3.1.2 面向对象的概念 8 第一篇 窗口与界面编程 3.1.3 面向组件的概念 3.2 面向对象的C#实现 3.2.1 ...

    ASP.NET 3.5 开发大全11-15

    2.7.4 try-catch-finally异常语句 2.8 小结 第3章 面向对象设计基础 3.1 什么是面向对象 3.1.1 传统的面向过程 3.1.2 面向对象的概念 3.1.3 面向组件的概念 3.2 面向对象的C#实现 3.2.1 定义 3.2.2 创建一个类和其...

    ASP.NET 3.5 开发大全

    2.7.4 try-catch-finally异常语句 2.8 小结 第3章 面向对象设计基础 3.1 什么是面向对象 3.1.1 传统的面向过程 3.1.2 面向对象的概念 3.1.3 面向组件的概念 3.2 面向对象的C#实现 3.2.1 定义 3.2.2 创建一个类和其...

    ASP.NET 3.5 开发大全1-5

    2.7.4 try-catch-finally异常语句 2.8 小结 第3章 面向对象设计基础 3.1 什么是面向对象 3.1.1 传统的面向过程 3.1.2 面向对象的概念 3.1.3 面向组件的概念 3.2 面向对象的C#实现 3.2.1 定义 3.2.2 创建一个类和其...

    ASP.NET 3.5 开发大全word课件

    2.7.4 try-catch-finally异常语句 2.8 小结 第3章 面向对象设计基础 3.1 什么是面向对象 3.1.1 传统的面向过程 3.1.2 面向对象的概念 3.1.3 面向组件的概念 3.2 面向对象的C#实现 3.2.1 定义 3.2.2 创建一个类和其...

    ASPNET35开发大全第一章

    2.7.4 try-catch-finally异常语句 2.8 小结 第3章 面向对象设计基础 3.1 什么是面向对象 3.1.1 传统的面向过程 3.1.2 面向对象的概念 3.1.3 面向组件的概念 3.2 面向对象的C#实现 3.2.1 定义 3.2.2 创建一个类和其...

Global site tag (gtag.js) - Google Analytics