我希望在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.
如果您始终希望在打印方法调用的结果后显示消息,请在方法调用之后打印它:
System.out.println(obj.divideTwoNumbers(sc.nextInt(),sc.nextInt()));
System.out.println("Thanks for using the application");
并删除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。感谢您使用应用程序