当我有如下代码时,编译器抱怨" test()方法必须返回int"
类型的结果class ExecptionExample {
public static void main(String[] args) {
System.out.println("Result :"+test());
}
private static int test(){
try{
System.out.println("In try");
throw new StackOverflowError("SOError");
} catch(Exception e){
System.out.println("In catch");
//throw new ArrayIndexOutOfBoundsException();
} finally{
System.out.println("In finally");
//throw new RuntimeException();
}
System.out.println("Outside try-catch");
//return 0;
}
}
如果我取消注释最后一行"返回0"然后它编译并运行但控制永远不会到达"返回0"并且从不打印"在try-catch"
之外考虑下面的代码,
class ExecptionExample {
public static void main(String[] args) {
System.out.println("Result :"+test());
}
private static int test(){
try{
System.out.println("In try");
throw new StackOverflowError("SOError");
} catch(Exception e){
System.out.println("In catch");
//throw new ArrayIndexOutOfBoundsException();
} finally{
System.out.println("In finally");
throw new RuntimeException();
}
//System.out.println("Outside try-catch");
//return 0;
}
}
在上面的代码中,编译器并没有抱怨"返回所需的int值"。
那么事情是如何运作的?编译器检查所需返回的规则是什么?
我在想,最后块总是会被执行(留下一些条件)并最终抛出RuntimeException
,所以编译器不需要返回int值?请确认我的理解。
我知道StackOverflowError
没有抓住Exception
。
我只想确认一件事,在finally块中抛出未经检查的异常,是编译器不会检查返回的原因吗?因为在没有finally块的情况下从try块中抛出未经检查的异常需要返回,并且在finally块中它不需要返回。
答案 0 :(得分:1)
这是因为最后你会抛出一个RuntimeException
,它会在从函数返回任何东西之前被抛出。
现在如果你在try块中放入return语句。异常仍将被抛出,因为finally块在返回数据之前执行(但在执行return语句之后)。但编译器不会给你任何错误。
但是如果在try-catch块编译器之后放置一个return语句会给你一个错误。这是因为try-catch块本身就抛出异常,编译器永远不会到达之后编写的代码。
答案 1 :(得分:0)
每当遇到异常时,程序都会中断并显示异常。它是否达到返回值无关紧要。这是为了防止执行任何不需要的条件。
答案 2 :(得分:0)
您可以检查try-catch-finally块以及它们的执行方式。关于它的信息很多(http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html)。
最后,block将始终在第一个示例中执行,您只执行syso,该方法不会结束,这就是为什么需要返回。在第二个中,您将抛出运行时,这将结束方法执行。
答案 3 :(得分:0)
无论finally
块返回什么,实际上都是Method的最终值。
public static void main(String[] args) {
System.out.println("Result :"+test());
}
private static int test(){
try{
System.out.println("In try");
return 5;
} catch(Exception e){
System.out.println("In catch");
return 5;
} finally{
System.out.println("In finally");
return 10; //finally return will be the final Return
}
// System.out.println("Outside try-catch");
//return 0;
}
输出将打印为10
。这意味着任何finally
块返回将是方法test()
的最终值。
现在来到你的问题。
问题1 。编译器抱怨
test() method must return a result of type int
?
答案: - 如果您定义return
类型除void
以外的方法,则必须返回类型或子类型变量。在无效状态下,无需return
任何值。
问题2 :我从最后一行
return 0
中删除了注释,然后编译并运行,但控件永远不会到达"返回0"并且永远不会打印"外部试用"。为什么?
答案: - 这将编译正常,因为只需删除您对第return
行的评论即可满足所需的return 0
值。
但是在你的尝试块中
throw new StackOverflowError("SOError"); // throwing an error which cannot be handled using Exception Handler in Catch Block
StackOverflowError
是error
而不是Exception
。所以,它不会在catch
Block中被捕获。因此,在finally
阻止后,您的方法将终止。控制权永远不会出现在本声明中。
System.out.println("Outside try-catch");
问题3 :为什么编译器不会抱怨
return int value required
??
Ans: - finally
阻止抛出Exception
这将是最后的Exception
语句将被执行,并且没有catch
块来处理这个问题。因此,方法test()
将在不处理任何返回值的情况下终止,并将Exception
委托给调用者语句(这是主要的)。
因此,它会compiles
很好但很容易出现Exception
。
谢谢。