try和catch块没有捕获异常,而是将结果作为无穷大

Instead of catching exceptions, the try and catch blocks give result as infinity

本文关键字:结果 无穷大 catch 捕获异常 try      更新时间:2023-10-16

在我的java和C++程序中,我都放置了一个简单的try/catch块来捕获被零除的异常。该项目没有解决这个问题,而是说答案是无限的。为什么会发生这种情况?

Java(C++几乎就是这样):

import java.util.Scanner;
import java.lang.ArithmeticException;
public class Expiriment {

    static double a;
    static double b;

    public static void main (String [] args){
        try {
        Scanner input = new Scanner (System.in);
            System.out.println("Enter first Number");
            a = input.nextInt();
            System.out.println("Enter 2nd number");
            b = input.nextInt();
            System.out.println("Answer is:"+ a/b);  
        }
        catch (ArithmeticException e) {
            double f = 0;
            System.err.println (e+" "+"Cannot perform operation.");
            System.out.println("Answer is:" + f);
        }

        }
    }
不要将Java的try/catch与C++的try/cach进行比较。在C++程序中被零除是而不是C++异常。

请看这里:

捕获异常:除以零

IEEE754浮点除法被定义为对于非零a和0 b返回无穷大,或者如果除以0/0则返回NaN。因此,您在打印报表中会得到这样的结果。

维基百科:

除以零(对有限操作数的运算会得到精确的无限结果,例如1/0log(0))(默认返回±infinity)。