Exceptions V2 - C# Programming Exercise

In this C# exercise, you are asked to write a program that prompts the user for a real number and displays its square root. Additionally, the program must handle any errors using a "try..catch" block.

The main goal of this exercise is to practice using the try..catch control structure in C#. This structure is essential for handling errors effectively in programs. In this case, the try block will attempt to calculate the square root of the entered number, and if the user enters a negative or non-numeric value (which would generate an error), the catch block will capture the error and provide an appropriate message to notify the user.

This exercise will help you understand how to handle exceptions in C# in a way that prevents the program from crashing unexpectedly. It will also familiarize you with C#'s mathematical functions and how they can be integrated into a robust control flow that prevents program failures.

 Category

Basic Data Types

 Exercise

Exceptions V2

 Objective

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?

 Write Your C# Exercise

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}");
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of Basic Data Types

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Char

    This exercise in C# aims to develop a program that asks the user for three letters and displays them in reverse order. The user will input one letter at...

  •  Triangle

    This exercise in C# aims to develop a program that prompts the user for a symbol and a width, and then displays a decreasing triangle of the spec...

  •  Password as string

    This exercise in C# aims to develop a program that asks the user for their username and password (both as strings) and repeats the prompt as many...

  •  Password 5 attempts

    This C# exercise involves creating a program that prompts the user for their username and password, both as strings. If the entered credentials do not m...

  •  Calculator - if

    This C# programming exercise requires creating a program that asks the user for two numbers and an operation to perform on them. The supported operations are ...

  •  Calculator - switch

    In this C# programming exercise, you need to create a program that asks the user for two numbers and a mathematical operation to perform between them. Supporte...