我在java方法代码中遇到问题,该方法返回两个数字的除数

问题描述 投票:0回答:2

在此代码中实现了除法,因此我想处理3种使用try catch和throws未定义除法的情况,但它给我一个错误消息,即除法必须返回float。包计算器3;

// Class实现接口公共类实现实现calc {

//Add function
    public int add(int x, int y) {
        int ans1 = x + y ; 
        return ans1 ;

    }

    //Divide function
    public float divide(int x, int y) throws RuntimeException{
        try {
            if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
                throw new ArithmeticException("invalid_division");

            }
            else {        
                return x / y ;
            }

        }catch  (ArithmeticException invalid_division ) {
            System.out.println("invalid_division");
        }
}
}   
java methods try-catch throw
2个回答
1
投票

您的divide返回类型为float

int永远不会等于Double.POSITIVE_INFINITYDouble.NEGATIVE_INFINITY,因为它们不在可能的值范围内。

如果被捕获,该函数将不会引发错误。

获得3分以上:

//divide
public float divide(int x, int y) throws ArithmeticException{
        if (y == 0) throw new ArithmeticException("invalid_division");
        return (float)x / y; // cast x to float so a float will result
}


0
投票

您在捕获到异常后实际上并未抛出异常,因此编译器将抱怨您在divide()方法中缺少返回值。

添加:

throw e;

到您的catch子句

© www.soinside.com 2019 - 2024. All rights reserved.