I'm trying to create a code that gives the factorial for a number given. If it is negative, string, or to large of a number an error should return. I figured out how to do the catch for the negative and string, but I'm confused on how to create a catch for a larger number. The teacher gave us this example but it really doesn't help. long f = 0; f = checked (a * b);
But I don't know which variables or what to do. Any help would be appreciated.
using System;
public class Factorial
{
public static void Main(string[] args)
{
bool continueLoop = true;
do
{
try
{
Console.Write("Enter a non-negative integer: ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0}! = {1}", number, factorial(number));
continueLoop = false;
}
catch ( FormatException)
{
Console.WriteLine("Invalid number format. Please try again.\n");
}
catch (NegativeNumberException negativeNumberException)
{
Console.WriteLine(negativeNumberException.Message);
}
catch (OverflowException)
{
int result = 0;
result = checked();
Console.WriteLine("Input value too large. Please try again.");
}
} while (continueLoop);
Console.ReadKey();
}// end Main
public static int factorial (int value)
{
if (value < 0)
throw new NegativeNumberException("Factorial of negative integer not permitted. Please try again\n");
else
return Factor(value);
}
public static int Factor(int number)
{
int result = 1;
for (int x = 1; x <= number; x++)
{
result *= x;
}
return result;
}
} // end class Factorial