如何从try和catch块中的return语句后的finally块中获取语句?

时间:2020-03-05 09:49:41

标签: java exception try-catch-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.

2 个答案:

答案 0 :(得分:1)

如果您始终希望在打印方法调用的结果后显示消息,请在方法调用之后打印该消息:

System.out.println(obj.divideTwoNumbers(sc.nextInt(),sc.nextInt()));
System.out.println("Thanks for using the application");

并删除finally

答案 1 :(得分:0)

最后总是在返回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。 感谢您使用该应用程序