`
sw1982
  • 浏览: 504797 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

蛋微疼的"Finally block does not complete normally"

阅读更多

今天用try-finally的时候,整出一个“finally block does not complete normally”的警告。想了半天也没明白什么一个情况。

 

可以看下面的代码, return 写在finally块就会得到警告!解决方案: return放到finally外面。

 

但是,java里面不是可以保证finally一定会执行的么,为什么不可以在finally块做return???

 

细细看道来:

 

debug一下这个函数,就会惊讶的发现, 里面抛出的异常会被finally吃掉。 这也就是为什么会被警告的原因。

	 @SuppressWarnings("finally")
	 private boolean isReturnWithinFinally() {
	 try {
	 if (true) throw new RuntimeException();
	 } finally {
	 return true; // This hides the exception
	 }
	 }

 

那么,下面这样会不会ok呢?先把异常处理

	public static void main(String[] args) {
		try{
			throw new RuntimeException();
		}catch(Exception e) {
			//
		}
		finally {
			return;
		}
	}

结论是:依旧不行。java里面的异常分为可不获和不可捕获两类,即便使用到catch块,也会导致非捕获的错误被finally吃掉。

 

因此,return一定要放到finally外面。

 

===1.java异常简介

类Throwable有两个直接子类:Error和Exception。Error类对象(如动态连接错误等),由Java虚拟 机生成并抛弃(通常,Java程序不对这类 异常进行处理) ;Exception类对象是Java程序处理或抛弃的对象。它有各种不同的子类分别对应于不同类型的例外。其中类RuntimeException代表运行时由Java虚拟机生成的 异常,如算术运算异常ArithmeticException(由除 0错等导致)、数组越界例外ArrayIndexOutOfBoundsException等;其它则为非运行时异常,如输入输出例外 IOException等。Java编译器要求 Java程序必须捕获或声明所有的非运行时异常 ,但对运行时异常 可以不做处理。

 

附赠示例代码一个:


 

 

=============================================================

2.参考文章:A Tale of Bad Exception Handling in Finally Blocks in Java。

老外开篇第一段文字,写的非常实在。于是我就坚持看完了全文,也找到了这个问题的答案

 

"There is always something more to learn . That was the lesson for me last week when I learned something new about the Java programming language, despite having used professionally it for almost 10 years."

  • 大小: 3.9 KB
  • 大小: 36.1 KB
分享到:
评论
4 楼 sw1982 2010-09-27  
第2个例子有问题,自己写的,和
3 楼 beneo 2010-09-27  
第二个的例子应该是
    private static boolean isReturnWithinFinally() {
        try {
            if (true)
                throw new RuntimeException("what the F");
        } finally {
             return true; // This hides the exception
        }
    }

2 楼 beneo 2010-09-27  
引用

14.1 Normal and Abrupt Completion of Statements

If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to complete normally. However, certain events may prevent a statement from completing normally:
The break (§14.15), continue (§14.16), and return (§14.17) statements cause a transfer of control that may prevent normal completion of statements that contain them.
Evaluation of certain expressions may throw exceptions from the Java virtual machine; these expressions are summarized in §15.6. An explicit throw (§14.18) statement also results in an exception. An exception causes a transfer of control that may prevent normal completion of statements.


这上面说的是break, continue, return都 may prevent normal completion of statements that contain them

举例子
    private static boolean isReturnWithinFinally() {
        try {
            if (true)
                throw new RuntimeException("what the F");
        } finally {
        }

        return true;
    }


这个finally里面是完全执行

    private static boolean isReturnWithinFinally() {
        try {
            if (true)
                throw new RuntimeException("what the F");
        } finally {
        }

        return true;
    }


这个就不是。。。。

*那么,在finally的return就破坏了throw E的条件,所以就不throw E。。

*还有一个问题,JLS上面写的是可以,那也就是说,其他的VM实现,表现出来的结果不一样。。
1 楼 beneo 2010-09-27  
我觉得你给的理由不是很充分

NPE,或者任何Exception子类都不是ERROR

问题应该在,为什么在fianlly里面的return,为什么会导致异常栈不能抛出。


根据
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#236078

引用

A try statement can throw an exception type E iff either:

The try block can throw E and E is not assignable to any catch parameter of the try statement and either no finally block is present or the finally block can complete normally; or
Some catch block of the try statement can throw E and either no finally block is present or the finally block can complete normally; or
A finally block is present and can throw E.


但是,JVM怎么实现这个功能的,我就找不出来了

相关推荐

    CommandFailedException.rar_out

    Thrown when an out of process executable does not return normally.

    squashfs1.3r3.tar.gz

    This is the default action if dest does not exist, or if no filesystem is on it -keep-as-directory If one source directory is specified, create a root directory containing that directory, ...

    Nonlinearequationssolver_非线性方程求解_fifteendvd_

    介绍非线性方程求解的函数,用法。附有m文件,供科研人员参考。

    Nand Flash ECC

    NOR Flash normally does not need ECC (Error-Correcting Code). On the other hand, NAND requires ECC to ensure data integrity. NAND Flash includes extra storage on each page to store ECC code as well ...

    fat-tailed and skewed asset return distributions

    evidence does not support the assumption that many important variables in finance follow a normal distribution. The application of the Central Limit Theorem to such instances is often inappropriate ...

    Universal-USB-Installer

    does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable ...

    2009 达内Unix学习笔记

    集合了 所有的 Unix命令大全 ...telnet 192.168.0.23 自己帐号 sd08077-you0 ftp工具 192.168.0.202 tools-toolss ... 各个 shell 可互相切换 ksh:$ sh:$ csh:guangzhou% bash:bash-3.00$ ... 命令和参数之间必需用空格隔...

    Normally-open-switch.rar_The Open Road

    Normally open switch, two road relay device.the control, time can be adjusted

    Windows MicroXP 0.82[Microsoft Windows XP SP3原版加工成的微型XP系统,=99.9%个完整XP]

    When you insert a CD that would bring up a screen to install the program contained on the CD, this does not happen in this version of Windows, you will have to explore the CD manually and run whatever...

    WizFlow网页编辑

    be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of ...

    hibernate-shards.jar

    be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of ...

    issrc-5.3.3.zip_The Front_delphi inno setup

    Compil32 does not do the actual compilation itself it relegates it to ISCmplr.dll. If the ISCmplr project is changed, you normally don t need to recompile Compil32 since it s essentially a text ...

    squashfs2.2-r2.tar.gz

    files which do not fit fully into a block, are NOT by default packed into fragments. To illustrate this, a 100K file has an initial 64K block and a 36K remainder. This 36K remainder is not packed into...

    Large displacement FEM modelling of the cone penetration test (CPT) in normally

    Large displacement FEM modelling of the cone penetration test (CPT) in normally

    lettuce-exit-normally

    问题 连接到集群后,JVM不会退出。 我该如何重现? 启动redis集群。 docker run -e "IP=0.0.0.0" -p 7000-7005:7000-7005 grokzen/redis-cluster:latest 然后运行: make test

    微软内部资料-SQL性能优化2

    Assuming the page reference does not result in an access violation, a page fault can be either hard or soft. A hard page fault results in a read from disk, either a page file or memory-mapped file. A...

    Python library

    on their semantics, but does not fully define the semantics. The library also contains built-in functions and exceptions — objects that can be used by all Python code without the need of an import ...

    LuaUnicode icu-lua

    string.sub(s, -3) will return the last 3 bytes of the string which is not necessarily the same as the last three characters of the string, and may or may not be a complete code. You could use the ...

    语音朗读精灵(SmartRead)

    What does not 不连接互联网时,会发生自动退出的情况。 Do not connect to the Internet, will automatically withdraw from the case. What was not tested 把文字转换成swf文件。 Text to swf file. ...

    High-Performance Normally-Off Al2O3/GaN MOSFET Using a Wet Etching-Based Gate Recess Technique

    High-Performance Normally-Off Al2O3/GaN MOSFET Using a Wet Etching-Based Gate Recess Technique

Global site tag (gtag.js) - Google Analytics