Thursday, October 21, 2010

Error Trapping

Here is the code that shows error trapping (AM Class)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace errortrapping
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.BadDivision();
Console.ReadKey();
}

void BadDivision()
{
double number;
double number2;
bool b1, b2;

try
{
Console.WriteLine("Enter a number");
b1 = double.TryParse(Console.ReadLine(), out number);

if (b1 == false)
{
Console.WriteLine("You must enter a real number");
return;
}

Console.WriteLine("Enter a second number");
b2 = double.TryParse(Console.ReadLine(), out number2);

if (b2 == false)
{
Console.WriteLine("You must enter a real number");
return;
}

if (number2 == 0)
{
throw new DivideByZeroException();
}

double quotient = number / number2;

Console.WriteLine("the quotient is {0}", quotient);
}//end try
catch (DivideByZeroException divError)
{
Console.WriteLine(divError.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}
}
}

No comments:

Post a Comment