Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 11 EXCEPTIONS

The try Statement

The try statement allows you to designate blocks of code to be guarded for exceptions and to supply code to handle them if they occur. The try statement consists of three sections, as shown in Figure 11-1.

The try block contains the code that is being guarded for exceptions.

The catch clauses section contains one or more catch clauses. These are blocks of code to handle the exceptions. They are also known as exception handlers.

The finally block contains code to be executed under all circumstances, whether or not an exception is raised.

Figure 11-1. Structure of the try statement

299

CHAPTER 11 EXCEPTIONS

Handling the Exception

The previous example showed that attempting to divide by zero causes an exception. You can modify the program to handle that exception by placing the code inside a try block and supplying a simple catch clause. When the exception is raised, it is caught and handled in the catch block.

static void Main()

{

int x = 10;

 

try

 

{

 

int y = 0;

 

x /= y;

// Raises an exception

}

 

catch

 

{

 

...

// Code to handle the exception

Console.WriteLine("Handling all exceptions - Keep on Running");

}

}

This code produces the following message. Notice that, other than the output message, there is no indication that an exception has occurred.

Handling all exceptions - Keep on Running

300

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]