try and Finally giving exception with no return statement , but there is no exception when return statement is written in method(try 和 finally 给出没有返回语句的异常,但是在方法中写入返回语句时没有异常)
问题描述
请解释为什么异常出现在第一个程序中,但没有出现在第二个程序中.
Please explain why Exception comes in first program but not in second program.
1) read 方法中没有返回语句
1) without return statement in read method
class Example
{
public static void read()
{
try
{
int i = 9/0;
}
finally
{
System.out.println("This proogram is giving exception");
}
}
public static void main(String[] fel)
{
read();
}
}
2)read方法中带有return语句
2)with return statement in read method
class Example
{
public static void read()
{
try
{
int i = 9/0;
}
finally
{
System.out.println("This proogram is not giving exception");
return;
}
}
public static void main(String[] fel)
{
read();
}
}
推荐答案
分支语句(return ,goto )不能在finally内部使用,因为执行这样的语句会使finally之前执行的其他指令无效.
Branching statements(return ,goto ) should no be used inside finally because execution of such statement nullifies other instructions which are executed before finally.
Java 语言规范 说:如果 try 块的执行由于任何其他原因 R 突然完成,则执行 finally 块,然后有一个选择:
The Java Language Specification says : If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:
- 如果 finally 块正常完成,则由于原因 R,try 语句会突然完成.
- 如果 finally 块由于原因 S 突然完成,则 try 语句由于原因 S 突然完成(并且原因 R 被丢弃).
注意 - finally 块中的 return 语句将导致 try 或 catch 块中可能引发的任何异常被丢弃.
Note - A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.
这篇关于try 和 finally 给出没有返回语句的异常,但是在方法中写入返回语句时没有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:try 和 finally 给出没有返回语句的异常,但是在方法中写入返回语句时没有异常


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01