简体   繁体   English

try-catch 块中的 if 语句返回“无限”

[英]if-statement inside a try-catch block returns "Infinite"

First of all i'm new to programming and just finished the Course on SoloLearn about C#.首先,我是编程新手,刚刚完成了有关 C# 的 SoloLearn 课程。 I do understand the core principal of try-catch blocks but i can't figure out how to correctly implement this in to my code(code shown below).我确实了解 try-catch 块的核心原理,但我无法弄清楚如何在我的代码中正确实现它(代码如下所示)。

class Program
{
    static void Main(string[] args)
    {   //create object of Class Calculator
        Calculator calc = new Calculator();

        //take user input and store in num1 and print it to screen
        try{
            double num1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("\nnumber1: " + num1);
            double num2 = Convert.ToInt32(Console.ReadLine());
            Console.Write("\nnumber2: " + num2);
        
            //take operator as input and print it to screen
            string operand = Console.ReadLine();
            Console.Write("\noperator: " + operand);

            //check if operator from user input is equal to one of the 4 calculation methods in Calculator Class
            Console.Write("\nresult: ");
            if(operand == "+"){
            Console.WriteLine(calc.Addition(num1, num2));
            }
            else if(operand == "-"){
            Console.WriteLine(calc.Subtraction(num1, num2));
            }
            else if(operand == "*"){
            Console.WriteLine(calc.Multiplication(num1, num2));
            }
            else{
            Console.WriteLine(calc.Division(num1, num2));
            }
        }
        catch(DivideByZeroException){
            Console.WriteLine("can't divide by zero");
        }
        catch(Exception e){
            Console.WriteLine("An error occurred. Only integers are allowed!");
        } 
    }
}//class Calculator with methods for 4 simple calculations
class Calculator{
    private double number1;
    private double number2;
    private double res;

    public double Addition(double num1, double num2){
        this.number1 = num1;
        this.number2 = num2;
        this.res = num1 + num2;
        return res;
    }
    public double Subtraction(double num1, double num2){
        this.number1 = num1;
        this.number2 = num2;
        this.res = num1 - num2;
        return res;
    }
    public double Multiplication(double num1, double num2){
        this.number1 = num1;
        this.number2 = num2;
        this.res = num1 * num2;
        return res;
    }
    public double Division(double num1, double num2){
        this.number1 = num1;
        this.number2 = num2;
        this.res = num1 / num2;
        return res;
    }
}

So i want my simple calculator to handle the exception "DivideByZero" and "Exception e" -> if the input was not an integer.所以我希望我的简单计算器能够处理异常“DivideByZero”和“Exception e”-> 如果输入不是整数。

When i test the DivideByZero Exception with an example input of 4/0, the programm returns "Infinite" as a result instead of the code from the catch block.当我使用 4/0 的示例输入测试 DivideByZero 异常时,程序返回“无限”作为结果,而不是来自 catch 块的代码。

I guess the "Infinite" result comes from the if-statements inside the try-catch block but i'm not sure.我猜“无限”结果来自 try-catch 块内的 if 语句,但我不确定。

I searched multiple sites, similar posts on stackoverflow and read the microsoft documentation for c# about try-catch blocks but i just can't figure it out.我搜索了多个站点,stackoverflow 上的类似帖子,并阅读了有关 try-catch 块的 c# 微软文档,但我就是想不通。

Sorry if my code sample is too big but i think this is the best way to understand my mess of code.对不起,如果我的代码示例太大,但我认为这是理解我的代码混乱的最佳方式。

Thank you in advance for the quick reply !预先感谢您的快速回复!

There is nothing wrong with your try catch.你的 try catch 没有任何问题。 If you divide a double by zero, you don't get an exception.如果将double除以零,则不会出现异常。 You get Double.PositiveInfinity as result in your case.在您的情况下,您会得到Double.PositiveInfinity The DivideByZeroException is only thrown for integer or decimal data types. DivideByZeroException仅针对整数或十进制数据类型引发。

Change fragment更改片段

 else {
   Console.WriteLine(calc.Division(num1, num2));
 }

into进入

 else {
   double v = calc.Division(num1, num2);

   Console.WriteLine(double.IsFinite(v) ? $"{v}" : "can't divide by zero");
}

Since floating point division doesn't throw exception but returns NaN , PositiveInfinity and NegativeInfinity :由于浮点除法不会抛出异常但返回NaNPositiveInfinityNegativeInfinity

 0.0 / 0.0 == double.NaN
 1.0 / 0.0 == double.PositiveInifinity
-1.0 / 0.0 == double.NegativeInfinity 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM