int? n = null;
string input;
while (n == null)
{
Console.WriteLine("Please enter a positive integer");
try
{
input = Console.ReadLine();
if (int.Parse(input) < 0)
{
Console.Write("Number must be a positive integer. ");
continue;
}
else if (!int.TryParse(input, out _))
{
throw new FormatException();
}
else if (int.TryParse(input, out _))
{
n = int.Parse(input);
}
}
catch (OverflowException o)
{
Console.Write("OverflowException. ");
}
catch (FormatException f)
{
Console.Write("FormatException. ");
}
}
int[] arr = new int[(int)n];
try
{
for (int i = 0; i < (int)n; i++)
{
Console.WriteLine("Enter number {0}", i + 1);
input = Console.ReadLine();
if (!int.TryParse(input, out _))
{
throw new FormatException("FormatException.");
}
else if (int.TryParse(input, out _))
{
arr[i] = int.Parse(input);
}
}
Console.WriteLine("Sum is " + Sum(arr));
}
catch (OverflowException o)
{
Console.WriteLine("OverflowException.");
}
catch (FormatException f)
{
Console.WriteLine("FormatException.");
}
//=======================================
static int Sum(int[] numbers)
{
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
return sum;
}