首页 > 解决方案 > 如何在 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.

标签: javaexceptiontry-catch-finally

解决方案


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。感谢您使用该应用程序


推荐阅读