Exercise
Exceptions V2
Objetive
Write a C# 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?
Example Code
using System; // Import the System namespace for basic functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
try
{
// Ask the user to enter a real number
Console.Write("Enter a real number: ");
double number = Convert.ToDouble(Console.ReadLine()); // Convert the input to a double
// Check if the number is negative before attempting to calculate the square root
if (number < 0)
{
// If the number is negative, throw an exception as we can't calculate the square root of a negative number
throw new InvalidOperationException("Cannot calculate the square root of a negative number.");
}
// Calculate and display the square root of the number
double squareRoot = Math.Sqrt(number);
Console.WriteLine($"The square root of {number} is {squareRoot}");
}
catch (FormatException)
{
// Catch the FormatException if the user doesn't input a valid number
Console.WriteLine("Error: Please enter a valid real number.");
}
catch (InvalidOperationException ex)
{
// Catch the InvalidOperationException if the number is negative
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
// Catch any other unexpected exceptions
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}