Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
35
Добавлен:
13.02.2015
Размер:
2.39 Mб
Скачать

You can also cause your own exceptions using the throw keyword.

Блоки finally

Код, содержащийся в блоке finally, выполняется всегда, вне зависимости от возникновения исключения. Чтобы гарантировать возвращение ресурсов, например, убедиться, что файл закрыт, используйте блок finally.

try

{

// Code to try here.

}

catch (SomeSpecificException ex)

{

// Code to handle exception here.

}

finally

{

// Code to execute after try (and possibly catch) here.

}

Использование обработки исключений

Исключения не всегда означают возникновение в программе серьезной проблемы. Часто с их помощью удобно оставить раздел кода, который больше не является релевантным, или они указывают на неудачное завершение метода. Большинство методов классов .NET Framework создают исключения для предупреждения об определенном условии.

Можно также вызвать собственные исключения, воспользовавшись ключевым словом throw.

For example:

class ProgramThrow

{

static void DoWork(int x)

{

if (x > 5)

{

throw new System.ArgumentOutOfRangeException("X is too large");

}

}

static void Main()

{

try

{

DoWork(10);

}

catch (System.ArgumentOutOfRangeException ex)

{

System.Console.WriteLine(ex.Message);

}

}

}

Use exceptions in your programs when you think there is a chance of some unexpected situation arising. For example, when dealing with input from a user, reading a file or accessing information from the Internet.

Пример

class ProgramThrow

{

static void DoWork(int x)

{

if (x > 5)

{

throw new System.ArgumentOutOfRangeException("X is too large");

}

}

static void Main()

{

try

{

DoWork(10);

}

catch (System.ArgumentOutOfRangeException ex)

{

System.Console.WriteLine(ex.Message);

}

}

}

Если предполагается возникновение неожиданной ситуации, рекомендуется использовать исключения. Они будут полезны, например, при работе с данными, введенными пользователями, чтении файла или доступе к сведениям из Интернета.

How to: Catch an Exception

This example uses try-catch blocks to catch division by zero as an exception. After the exception is caught, the execution is resumed in the finally block.

Example

int top = 0, bottom = 0, result = 0;

try

{

result = top / bottom;

}

catch (System.Exception ex)

{

System.Console.WriteLine("{0} exception caught here.", ex.GetType().ToString());

System.Console.WriteLine(ex.Message);

}

finally

{

System.Console.WriteLine("Clean-up code executes here...");

}

System.Console.WriteLine("Program execution continues here...");

//Oputput

System.DivideByZeroException exception caught here.

Attempted to divide by zero.

Clean-up code executes here...

Program execution continues here...

Compiling the Code

Copy the code and paste it into the Main method of a console application.

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