Exceptions V2 Learn programming C#

Lesson:

Basic Data Types


Exercise:

Exceptions V2


Objetive:

Create a program to ask the user for a real number and display its square root. Errors must be trapped using "try..catch".

Does it behave as you expected?


Code:

using System;
public class exercise71
{
    public static void Main()
    {
        float result;
        float num;

        Console.Write("Enter Number ");
        try
        {
            num = Convert.ToSingle(Console.ReadLine());

            result = (float)Math.Sqrt(num);
            Console.WriteLine("The result is: {0}", result);
        }
        catch (Exception)
        {
            Console.WriteLine("Error, I cannot calculate the Square Root");
        }
    }
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.