In: Computer Science
This question has been answered already however, I'd like some new examples.
Task: In C#, create a minimum of three try/catch statements that would handle potential input errors. Thank you.
Taking 3 try-catch for 3 exceptions:
1) NotaPositiveNumberException
2) InvalidUserNameException
3) IndexOutOfRangeException
Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TryCatchDemo
{
class NotaPositiveNumberException : ApplicationException
{
public NotaPositiveNumberException(string str) : base(str)
{ }
}
class InvalidUserNameException : ApplicationException
{
public InvalidUserNameException(string str) : base(str)
{ }
}
class Program
{
static void Main(string[] args)
{
//1. try..catch
//NotaPositiveNumberException
int number;
try
{
Console.WriteLine("---------------------------------------------------");
Console.Write("Enter a positive number: ");
number = Convert.ToInt32(Console.ReadLine());
if (number < 0)
{
throw new NotaPositiveNumberException("InvalidNumber");
}
else
{
Console.WriteLine("The entered number is a positive
number!");
}
}
catch (NotaPositiveNumberException n1)
{
Console.WriteLine("The number is not a positive number!!");
}
Console.WriteLine("---------------------------------------------------");
//2. try..catch
//InvalidUserName - Enter a name that should not be greater than 15
characters
string userName;
try
{
Console.Write("\nEnter an username(less than 15 characters):
");
userName = Console.ReadLine();
if (userName.Length > 15)
{
throw new InvalidUserNameException("InvalidUserName");
}
else
{
Console.WriteLine("\nValid Username!!");
}
}
catch (InvalidUserNameException ie)
{
Console.WriteLine("\nThe length of a username should not be greater
than 15 characters!");
}
Console.WriteLine("---------------------------------------------------");
//3. try..catch
//IndexOutOFBoundException - Array
//Enter the index to show the element
int[] arr = new int[5];
int index;
//enter 5 elements
Console.WriteLine("\n\nEnter 5 elements: ");
for (int i = 0; i < 5; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
try
{
Console.WriteLine("Enter the index to show the element: ");
index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The element is "+arr[index]);
}
catch (IndexOutOfRangeException ie)
{
Console.WriteLine("\nInvalid index number!!");
Console.WriteLine("\nArray index out of bound exception!");
}
Console.WriteLine("---------------------------------------------------");
Console.ReadKey();
}
}
}
Output: