To demonstrate the importance of order of exception handlers, write two programs
ID: 3540080 • Letter: T
Question
To demonstrate the importance of order of exception handlers, write two programs, one with correct ordering of catch blocks (ie, place the base-class exception handler after all derived-class exception handlers) and another with improper ordering (i.e, place the base-class exception handler before the derived-class exception handlers). So this is pretty simple. The first program will successfully catch an exception, and the second program will not run successfully and will display errors. C# only please!!
Explanation / Answer
Hi ,
I am using the DivideBy Zero exception as the test case.
int y = 100;
int x = 0;
string txt="0";
try
{
Console.WriteLine(y / x);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
In the above code, the exception is caught by the first block(derived class handler) itself and does not go the base class handler.
The second program is to modify the first program - by placing the base class handler above the derived class handler. This program will not compile and give compilation errors.
int y = 100;
int x = 0;
string txt="0";
try
{
Console.WriteLine(y / x);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
Console.Read();
If yu want to use a different example for your secnd program, then use this
string txt="a";
try
{
Convert.ToInt32(txt);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.