183k views
2 votes
Write an exception tester application that enables you to see the impact of exceptions being thrown. Include multiple catch clauses. Include the ArithmeticException, FormatException, IndexOutOfRangeException, and Exception classes. For each exception, write a try block containing errors to throw the exceptions. As you test the application, include an error that throws the exception and then comment it out and program an error that throws the next exception and so on. Your final solution should include at least one statement per exception that throws each exception. The statements should all be commented out by the time you finish testing. Be sure to include documenting comments with each statement.

User Lee Irvine
by
7.1k points

1 Answer

2 votes

Answer:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("\t\tHandling Exceptions Program");

Console.WriteLine("\\\tArithmetic Exception:\\");

// Arithmetic Exception is base class of DivideByZero Class

// Hence will be using DivideByZero Exception

int b = 0;

try

{

//Attempting Divide BY Zero

int myBadMath = (5 / b);

}

catch (System.DivideByZeroException ex)

{

Console.WriteLine("Error : Trying to divide a number by Zero");

}

//FormatException example

//Used when formats DO NOT match a data type

Console.WriteLine("\\\tFormat Exception:\\");

Console.WriteLine("Please enter a number :");

string str = Console.ReadLine();

double dNo;

try

{

//throws exception when a string is entered instead of a number

dNo = Convert.ToDouble(str);

Console.WriteLine(dNo+" : Is a valid number");

}

catch (FormatException ex)

{

Console.WriteLine("Error : "+str+" is not a valid number");

}

//IndexOutOfRangeException example

//Thrown when an element is attempted to assign or read out of the array size

Console.WriteLine("\\\tIndexOutOfRangeException Exception:\\");

try

{

//5 element array declared

int[] IntegerArray = new int[5];

//attempting 10th element. Hence error is thrown

IntegerArray[10] = 123;

}

catch (IndexOutOfRangeException)

{

Console.WriteLine("An invalid element index access was attempted.");

Console.Read();

}

}

}

}

Step-by-step explanation:

User Joviano Dias
by
7.6k points