2010-09-21 43 views
1
public class Test2 { 
    public static void main(String args[]) { 

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

    public static int method() { 
     try { 
      throw new Exception(); 
      return 1; 
     } catch (Exception e) { 
      return 2; 
     } finally { 
      return 3; 
     } 
    } 
} 

try块抛出有return语句,并抛出异常也... 其输出为编译器错误....return语句,并在Java

我们知道,finally块覆盖try/catch块中的返回值或异常声明... 但这个问题已经在try块中... 为什么输出错误?

+2

你介意与我们分享实际的编译器错误吗?虽然这是一个相当平凡的案例,但通常情况下,通过发布不完整/不明确的问题,可以减少获得良好答案的机会。 – 2010-09-21 08:30:39

回答

14

因为您的return语句无法访问 - 执行流程永远无法到达该行。

如果throw声明在if条款中,那么return将可能可达,并且错误将消失。但在这种情况下,在那里有return没有意义。

另一个重要的注意事项 - 避免从finally子句返回。例如,Eclipse编译器在finally子句中显示有关return语句的警告。

+0

当然。加1. – 2010-09-21 08:34:41

+0

很好。 +1为您的答案 – 2010-09-21 09:08:57

+0

@Bozho:+ 1.请编辑您的投掷掷出 – 2013-06-09 05:14:49

2

无论如何,throw new Exception()都会被调用,所以在try块内的任何东西都是不可达代码。因此错误。

2
public class Test2 { 
    public static void main(String args[]) { 

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

    public static int method() { 
     try { 
      throw new Exception(); 
      return 1; //<<< This is unreachable 
     } catch (Exception e) { 
      return 2; 
     } finally { 
      return 3; 
     } 
    } 
} 

应该最终回归3.

6

编译器例外从何而来,就像我的Eclipse伙计说

Unreachable code Test2.java line 11 Java Problem 

主代码块的return语句将永远不会被达到,作为异常被抛出之前。

阿洛斯注意到你的finally块,至少,一个设计缺陷,如Eclipse再次表示return语句

finally block does not complete normally Test2.javajava line 14 Java Problem 

事实上,作为一个finally块这里只是提供一些干净的关闭,它预计不会返回会覆盖该方法通常返回的结果的内容。

+1

+1。我知道你想说“设计缺陷”而不是“设计法”:) – helios 2010-09-21 08:55:47

+0

@helios我修正了错字。感谢您的更正! – Riduidel 2010-09-21 09:24:31

0

由于try块中的'return'关键字无法访问,这就是为什么你得到编译时错误。忽略try块中的'return'关键字,然后运行你的程序,你的程序将成功编译。