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

CHAPTER 11 EXCEPTIONS

Throwing Exceptions

You can make your code explicitly raise an exception by using the throw statement. The syntax for the throw statement is the following:

throw ExceptionObject;

For example, the following code defines a method called PrintArg, which takes a string argument and prints it out. Inside the try block, it first checks to make sure the argument is not null. If it is, it creates an ArgumentNullException instance and throws it. The exception instance is caught in the catch statement, and the error message is printed. Main calls the method twice: once with a null argument and then with a valid argument.

class MyClass

 

{

 

public static void PrintArg(string arg)

 

{

 

try

 

{

Supply name of null argument

if (arg == null)

{

ArgumentNullException myEx = new ArgumentNullException("arg"); throw myEx;

}

Console.WriteLine(arg);

}

catch (ArgumentNullException e)

{

Console.WriteLine("Message: {0}", e.Message);

}

}

}

class Program

{

static void Main()

{

string s = null; MyClass.PrintArg(s); MyClass.PrintArg("Hi there!");

}

}

This code produces the following output:

Message: Value cannot be null.

Parameter name: arg

Hi there!

313

CHAPTER 11 EXCEPTIONS

Throwing Without an Exception Object

The throw statement can also be used without an exception object, inside a catch block.

This form rethrows the current exception, and the system continues its search for additional handlers for it.

This form can be used only inside a catch statement.

For example, the following code rethrows the exception from inside the first catch clause:

class MyClass

{

public static void PrintArg(string arg)

{

try

{

try

{

if (arg == null)

Supply name of null argument

{

 

 

ArgumentNullException myEx = new ArgumentNullException("arg"); throw myEx;

}

Console.WriteLine(arg);

}

catch (ArgumentNullException e)

{

Console.WriteLine("Inner Catch: {0}", e.Message); throw;

}

}Rethrow the exception, with no additional parameters

catch

{

Console.WriteLine("Outer Catch: Handling an Exception.");

}

}

}

class Program {

static void Main() { string s = null; MyClass.PrintArg(s);

}

}

314

CHAPTER 11 EXCEPTIONS

This code produces the following output:

Inner Catch: Value cannot be null.

Parameter name: arg

Outer Catch: Handling an Exception.

315

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