 |
C# Examples: Throwing an Exception
|
|
This is an example of using the throw keyword to throw a
specific exception:
|
using System;
class Exercise
{
static void Main()
{
double Operand1, Operand2;
double Result = 0.00;
char Operator;
Console.WriteLine("This program allows you to perform an operation on two numbers");
try
{
Console.WriteLine("To proceed, enter a number, an operator, and a number:");
Operand1 = double.Parse(Console.ReadLine());
Operator = char.Parse(Console.ReadLine());
Operand2 = double.Parse(Console.ReadLine());
if( Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/')
throw new Exception(Operator.ToString());
switch(Operator)
{
case '+':
Result = Operand1 + Operand2;
break;
case '-':
Result = Operand1 - Operand2;
break;
case '*':
Result = Operand1 * Operand2;
break;
case '/':
Result = Operand1 / Operand2;
break;
default:
Console.WriteLine("Bad Operation");
break;
}
Console.WriteLine("\n{0} {1} {2} = {3}", Operand1, Operator, Operand2, Result);
}
catch(Exception ex)
{
Console.WriteLine("\nOperation Error: {0} is not a valid operator", ex.Message);
}
}
}