w3resource

C# Program: Calculate factorial with overflow exception handling

C# Sharp Exception Handling: Exercise-12 with Solution

Write a C# program that creates a method that calculates the factorial of a given number. Handle the OverflowException that occurs if the result exceeds the Int32 maximum value.

Sample Solution:

C# Sharp Code:

using System;

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

      // Calculate factorial of the entered number
      int factorial = CalculateFactorial(number);

      // Display the calculated factorial
      Console.WriteLine("Factorial: " + factorial);
    } catch (OverflowException) {
      // Catch block for handling OverflowException (if the factorial exceeds Int32.MaxValue)
      Console.WriteLine("Error: Factorial exceeds the maximum value of Int32.");
    } catch (FormatException) {
      // Catch block for handling FormatException (invalid input format)
      Console.WriteLine("Error: Invalid input. Please enter a valid number.");
    } catch (Exception ex) {
      // Catch block for handling other types of exceptions
      Console.WriteLine("An error occurred: " + ex.Message);
    }
  }

  // Method to calculate the factorial of a number
  static int CalculateFactorial(int number) {
    // Check if the input number is negative
    if (number < 0) {
      // Throw an ArgumentException for negative input numbers
      throw new ArgumentException("Number must be non-negative.");
    }

    // Initialize the factorial as 1
    int factorial = 1;

    // Loop to calculate the factorial
    for (int i = 1; i <= number; i++) {
      checked {
        // Multiply the current value of factorial with the loop variable (i)
        factorial *= i; // The checked keyword checks for overflow and throws an OverflowException if detected
      }
    }

    // Return the calculated factorial value
    return factorial;
  }
}

Sample Output:

Input a positive number (integer): 1000
Error: Factorial exceeds the maximum value of Int32.
  
Input a positive number (integer): 10
Factorial: 3628800
  
Input a positive number (integer): -7
An error occurred: Number must be non-negative. 
 
Input a positive number (integer): 3.4
Error: Invalid input. Please enter a valid number.

Explanation:

In the above exercise,

  • The "Main()" method prompts the user to input a positive number (integer). The input is converted to an int using Convert.ToInt32() and stored in the number variable.
  • The program calls the "CalculateFactorial()" method, passing the number as an argument.
  • The CalculateFactorial method checks if the number is less than 0. If it is, an ArgumentException is thrown with an appropriate error message.
  • Inside the "CalculateFactorial()" method, a for loop calculates the factorial of the given number. The checked keyword ensures that an OverflowException is thrown if the result exceeds Int32's maximum value.
  • In the "Main()" method, exceptions are handled using catch blocks. If an OverflowException occurs, it means the number's factorial exceeds the Int32 maximum value. The program catches this exception and displays an appropriate error message. If a FormatException occurs, it means the input was not a valid number. The program catches this exception and displays an appropriate error message.
  • Any other exceptions are caught by the generic catch block, and a general error message is displayed.
  • The program displays the calculated factorial using Console.WriteLine.

Flowchart:

Flowchart: Calculate factorial with overflow exception handling.

Flowchart: Calculate factorial with overflow exception handling.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Convert string to uppercase with exception handling.
Next: Download content from multiple URLs with exception handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/exception-handling/csharp-exception-handling-exercise-12.php