Programming Course in C# ¡Free!

Exceptions

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

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?


Output



Solution


using System;
public class TSqrt
{
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");
}
}
}