by offering some ways to remedy the problem instead of exiting midway through your program (that is, crashing).

Handling Exceptions

To understand the importance of handling exceptions, consider the following case, a classic example of dividing two numbers:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApp {

 class Program {

  static void Main(string[] args) {

   int num1, num2, result;

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

   Console.ReadLine();

  }

 }

}

In this example, there are several opportunities for exceptions to occur:

□ If the user enters a noninteger value for num1 or num2.

□ If the user enters a non-numeric value for num1 and num2.

□ If num2 is zero, resulting in a division by zero error.

Figure 12-1 shows the program halting abruptly when the user enters 3.5 for num1.

Figure 12-1

Hence, you need to anticipate all the possible scenarios and handle the exceptions gracefully.

Handling Exceptions Using the try-catch Statement

In C#, you can use the try-catch statement to enclose a block of code statements that may potentially cause exceptions to be raised. You enclose these statements within the catch block and that block to catch the different types of exceptions that may occur.

Using the previous example, you can enclose the statements that ask the user to input num1 and num2 and then performs the division within a try block. You then use the catch block to catch possible exceptions, like this:

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 (Exception ex) {

  Console.WriteLine(ex.Message);

 }

 Console.ReadLine();

}

The Exception class is the base class for all exceptions; that is, it catches all the various types of exceptions. The class contains the details of the exception that occurred, and includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception. The following table describes these properties.

Property Description
Data Gets a collection of key/value pairs that provide additional user-defined information about the exception.
HelpLink Gets or sets a link to the help file associated with this exception.
HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
InnerException Gets the Exception instance that caused the current exception.
Message Gets a message that describes the current exception.
Source Gets or sets the name of the application or the object that causes the error.
StackTrace
Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

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

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