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 给出没有返回语句的异常,但是在方法中写入返回语句时没有异常
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
