Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite Gets the method that throws the current exception.

In the preceding program, if you type in a numeric value for num1 and then an alphabetical character for num2, the exception is caught and displayed like this:

Please enter the first number:6

Please enter the second number:a

Input string was not in a correct format.

If, though, you enter 0 for the second number, you get a different description for the error:

Please enter the first number:7

Please enter the second number:0

Attempted to divide by zero.

Notice that two different types of exceptions are caught using the same Exception class. The description of the exception is contained within the Message property of the Exception class.

You can use the ToString() method of the Exception class to retrieve more details about the exception, such as the description of the exception as well as the stack trace.

However, there are cases where you would like to print your own custom error messages for the different types of exceptions. Using the preceding code, you would not be able to do that — you would need a much finer way to catch the different types of possible exceptions.

To know the different types of exceptions that your program can cause (such as entering 'a' for num1 or division by zero), you can set a breakpoint at a line within the catch block and try entering different values. When an exception is raised during runtime, IntelliSense tells you the error and the type of the exception raised. Figure 12-2 shows that the FormatException exception is raised when you enter a for num1.

Figure 12-2

If you are not sure what type of exception your program is going to raise during runtime, it is always safe to use the base Exception class. If not — if the exception that is raised does not match the exception you are trying to catch — a runtime error will occur. Here's an example:

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());

  result = num1 / num2;

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

 } catch (DivideByZeroException ex) {

  Console.WriteLine(ex.Message);

 }

 Console.ReadLine();

}

If a division-by-zero exception occurs (entering 0 for num2), the exception is caught. However, if you enter an alphabetic character for num1 or num2, a FormatException exception is raised. And because you are only catching the DivideByZeroException exception, this exception goes unhandled and a runtime error results.

Handling Multiple Exceptions

To handle different types of exceptions, you can have one or more catch blocks in the try-catch statement. The following example shows how you can catch three different exceptions:

□ DivideByZeroException — Thrown when there is an attempt to divide an integral or decimal value by zero.

□ FormatException — Thrown when the format of an argument does not meet the parameter specifications of the invoked method.

□ Exception — Represents errors that occur during application execution.

This example handles the three different exceptions and then prints out a custom error message:

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());

 result = num1 / num2;

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

 } catch (DivideByZeroException ex) {

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

 } catch (FormatException ex) {

  Console.WriteLine('Input error.');

 } catch (Exception ex) {

  Console.WriteLine(ex.Message);

 }

 Console.ReadLine();

}

In this program, typing in a numeric value for num1 and an alphabetic character for num2 produces the FormatException exception, which is caught and displayed like this?

Please enter the first number:6

Please enter the second number:a

Input error.

Entering 0 for the second number throws the DivideByZeroException exception, which is caught and displays a different error message:

Please enter the first number:7

Please enter the second number:0

Division by zero error.

So far, all the statements are located in the Main() function. What happens if you have a

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

0

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

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