w3resource

C# Program: Calculate square root with exception handling

C# Sharp Exception Handling: Exercise-10 with Solution

Write a C# program that reads a number from the user and calculates its square root. Handle the exception if the number is negative.

Sample Solution:

C# Sharp Code:

using System;

class Program {
  static void Main() {
    try {
      // Ask the user to input a number
      Console.Write("Input a number: ");
      double number = Convert.ToDouble(Console.ReadLine());

      // Check if the input number is non-negative
      if (number >= 0) {
        // Calculate the square root if the number is non-negative
        double squareRoot = CalculateSquareRoot(number);
        Console.WriteLine("Square root: " + squareRoot);
      } else {
        // Throw an ArgumentException if the number is negative
        throw new ArgumentException("Number cannot be negative!");
      }
    } catch (FormatException) {
      // Catch block for handling FormatException (invalid input)
      Console.WriteLine("Error: Invalid input. Please input a valid number.");
    } catch (ArgumentException ex) {
      // Catch block for handling ArgumentException (negative number)
      Console.WriteLine("Error: " + ex.Message);
    } catch (Exception ex) {
      // Catch block for handling other types of exceptions
      Console.WriteLine("An error occurred: " + ex.Message);
    }
  }

  // Method to calculate the square root of a number
  static double CalculateSquareRoot(double number) {
    // Using the Math.Sqrt method to calculate the square root
    return Math.Sqrt(number);
  }
}

Sample Output:

Input a number: 12
Square root: 3.4641016151377544
  
Input a number: -25
Error: Number cannot be negative!
  
Input a number: 100
Square root: 10

Explanation:

In the above exercise -

  • The "Main()" method prompts the user to input a number using Console.Write() and Console.ReadLine(). The input is converted to a double using Convert.ToDouble() and stored in the number variable.
  • The program checks if the number is greater than or equal to 0. If it is, the square root is calculated using the CalculateSquareRoot method and stored in the squareRoot variable. If the number is negative, an ArgumentException is thrown with an appropriate error message.
  • In the "Main()" method, exceptions are handled using catch blocks. If a FormatException occurs, it means the input was not a valid number. The program catches this exception and displays an appropriate error message. If an ArgumentException occurs, the user entered a negative number. The program catches this exception and displays the error message contained within the exception.
  • Any other exceptions are caught by the generic catch block, and a general error message is displayed.
  • If no exceptions occur, the program displays the calculated square root using Console.WriteLine.

Flowchart:

Flowchart: Calculate square root with exception handling.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Convert user input to datetime with exception handling.
Next: Convert string to uppercase with exception handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.