Console.Write('Please enter the second number:');

  num2 = int.Parse(Console.ReadLine());

  Program myApp = new Program();

  Console.WriteLine('The result of {0}/{1} is {2}', num1, num2,

   myApp.PerformDivision(num1, num2));

 } catch (DivideByZeroException ex) {

  Console.WriteLine('Division by zero error.');

 } catch (ArithmeticException ex) {

  Console.WriteLine('Numerator cannot be zero.');

 } catch (FormatException ex) {

  Console.WriteLine('Input error.');

 } catch (Exception ex) {

  Console.WriteLine(ex.Message);

 }

 Console.ReadLine();

}

The following shows the output when different values are entered for num1 and num2:

Please enter the first number:5

Please enter the second number:0

Division by zero error.

Please enter the first number:0

Please enter the second number:5

Numerator cannot be zero.

Please enter the first number:a

Input error.

Rethrowing Exceptions

There are times when after catching an exception, you want to throw the same (or a new type) exception back to the calling function after taking some corrective actions. Take a look at this example:

class Program {

 static void Main(string[] args) {

  int num1, num2, result;

  try {

   Console.Write('Please enter the first number:');

   num1 = int.Parse(Console.ReadLine());

   Console.Write('Please enter the second number:');

   num2 = int.Parse(Console.ReadLine());

   Program myApp = new Program();

   Console.WriteLine('The result of {0}/{1} is {2}', num1, num2,

    myApp.PerformDivision(num1, num2));

  } catch (Exception ex) {

   Console.WriteLine(ex.Message);

   if (ex.InnerException != null)

    Console.WriteLine(ex.InnerException.ToString());

  }

  Console.ReadLine();

 }

 private int PerformDivision(int num1, int num2) {

  try {

   return num1 / num2;

  } catch (DivideByZeroException ex) {

   throw new Exception('Division by zero error.', ex);

  }

 }

}

Here, the PerformDivision() function tries to catch the DivideByZeroException exception and once it succeeds, it rethrows a new generic Exception exception, using the following statements with two arguments:

throw new Exception('Division by zero error.', ex);

The first argument indicates the description for the exception to be thrown, while the second argument is for the inner exception. The inner exception indicates the exception that causes the current exception. When this exception is rethrown, it is handled by the catch block in the Main() function:

catch (Exception ex) {

 Console.WriteLine(ex.Message);

 if (ex.InnerException != null)

  Console.WriteLine(ex.InnerException.ToString());

}

To retrieve the source of the exception, you can check the InnerException property and print out its details using the ToString() method. Here's the output when num2 is zero:

Please enter the first number:5

Please enter the second number:0

Division by zero error.

System.DivideByZeroException: Attempted to divide by zero.

 at ConsoleApp.Program.PerformDivision(Int32 num1, Int32 num2) in C:Documents and Settings Wei-Meng LeeMy DocumentsVisual Studio 2008ProjectsConsoleAppConsoleAppProgram.cs:line 43

As you can see, the message of the exception is 'Division by zero error' (set by yourself) and the InnerException property shows the real cause of the error — 'Attempted to divide by zero.'

Exception Chaining

The InnerException property is of type Exception, and it can be used to store a list of previous exceptions. This is known as exception chaining.

To see how exception chaining works, consider the following program:

class Program {

 static void Main(string[] args) {

  Program myApp = new Program();

  try {

   myApp.Method1();

  } catch (Exception ex) {

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату