java - 如何在 try 和 catch 块的 return 语句之后打印 finally 块中的语句?
问题描述
我希望finally
块中的语句在 return 语句之后打印try and catch block
,但 finally 块中的语句总是在此之前打印。
1 import java.io.*;
2 import java.util.*;
3 public class Division
4 {
5 public String divideTwoNumbers(int number1,int number2)
6 {
7 try
8 {
9 int n=number1/number2;
10 String ans="The answer is "+n+".";
11 return ans;
12
13 }
14 catch(ArithmeticException e)
15 {
16 String s1="Division by zero is not possible. ";
17 return s1;
18 }
19 finally
20 {
21 System.out.print("Thanks for using the application");
22 }
23 }
24 public static void main(String[] args)
25 {
26 Division obj=new Division();
27 Scanner sc=new Scanner(System.in);
28 System.out.println("Enter the numbers");
29 System.out.println(obj.divideTwoNumbers(sc.nextInt(),sc.nextInt()));
30 }
31 }
对于输入:
`15` and `0`
需要的输出:
`Division by zero is not possible. Thanks for using the application.`
我得到的输出:
Thanks for using the application. Division by zero is not possible.
解决方案
finally 总是在返回 ans 值之前执行。
import java.io.*;
import java.util.*;
public class Division {
public String divideTwoNumbers(int number1, int number2) {
try {
int n = number1 / number2;
String ans = "The answer is " + n + ".";
return ans;
} catch (ArithmeticException e) {
String s1 = "Division by zero is not possible. ";
return s1;
}
}
public static void main(String[] args) {
try {
Division obj = new Division();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers");
System.out.println(obj.divideTwoNumbers(sc.nextInt(), sc.nextInt()));
}
finally {
System.out.print("Thanks for using the application");
}
}
}
输出:输入数字 15 3 答案是 5。感谢您使用该应用程序
推荐阅读
- python - 热门创建绘图以可视化结构的模式
- redirect - 重定向回原点时被 CORS 策略阻止:标头的值 ... 不等于提供的原点
- python - 在电力预测中使用 Keras 的 lstm 和 ANN 的比较
- javascript - 无法将数据从反应发送到快递服务器
- wso2 - 我目前正在使用 WSO2 ESB 4.8.1,我想知道是否可以延迟 ESB 服务响应
- html - 使用 flexbox div 进行响应式设计
- flutter - 将大量数据插入 Flutter Hive 存储使应用程序崩溃
- twitter-bootstrap - 如何去除这些卡片周围的填充和边距?
- javascript - 将边框半径赋予 svg 并更改字体大小
- apache-kafka - Kafka 删除段时出错 -> 进程无法访问该文件,因为它正被另一个进程使用