简体   繁体   中英

Where i should place try catch block? (Simple division method)

It's my code:

 using System;

 using System.Data;

 using System.Transactions;

 namespace BasicCourse.Exceptions 
 {

    class Program
    {
   
       static void Main(string[] args)
       {
       
       Division();

       Console.ReadKey();
       }

      static void Division()
      {
        Console.Write("Enter a first number: ");
        int firstEnteredNumber = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        int secondEnteredNumber = int.Parse(Console.ReadLine());

        float quotient = (float) firstEnteredNumber / secondEnteredNumber;

        Console.WriteLine("Result of division: " + quotient + "\n");
      }
}

}

I'm learning the exceptions in C#.I want to attend the divide by zero exception but i don't know where should i place a try catch block.In Main method:

try 
{ 
    Division() 
} 
catch (DivideByZeroException ex)
 etc...? 

Or inside the Division method?

        static void Main(string[] args)
    {
        try
        {
            Division();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }


        Console.ReadKey();
    }

Dividing by zero doesn't result in an exception. You would have to put in some logic to handle it.

            if (float.IsNaN(quotient))
        {
            //dostuff
        }

Update --- Sorry!
I read others' answers and found that float don't throw any exceptions!I'm so sorry for I forgot it.

DivideByZeroException Class
The exception that is thrown when there is an attempt to divide an integral or decimal value by zero.

The console shows:

Result of division: ∞

In fact, we don't want this type of result, so I edited the answer.


So we know the result is: no exception throwed.
If you want method Division() to remind users that they are trying to divide by 0, you can check the value.

      static void Division()
      {
        Console.Write("Enter a first number: ");
        int firstEnteredNumber = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        int secondEnteredNumber = int.Parse(Console.ReadLine());

        //Added
        if (secondEnteredNumber == 0)
        {
            Console.WriteLine("cannot divide by 0");
        }
        else
        {
            float quotient = (float) firstEnteredNumber / secondEnteredNumber;
            Console.WriteLine("Result of division: " + quotient + "\n");
        }
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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