logo search
CSharp_Prog_Guide

Общие сведения об исключениях

Исключения имеют следующие свойства.

Using Exceptions

In C#, errors in the program at run time are propagated through the program by using a mechanism called exceptions. Exceptions are thrown by code that encounters an error and caught by code that can correct the error. Exceptions can be thrown by the .NET Framework common language runtime (CLR) or by code in a program. Once an exception is thrown, it propagates up the call stack until a catch statement for the exception is found. Uncaught exceptions are handled by a generic exception handler provided by the system that displays a dialog box.

Exceptions are represented by classes derived from Exception. This class identifies the type of exception and contains properties that have details about the exception. Throwing an exception involves creating an instance of an exception-derived class, optionally configuring properties of the exception, and then throwing the object by using the throw keyword. For example:

class CustomException : Exception

{

public CustomException(string message)

{

}

}

private static void TestThrow()

{

CustomException ex =

new CustomException("Custom exception in TestThrow()");

throw ex;

}

After an exception is thrown, the runtime checks the current statement to see whether it is within a try block. If it is, any catch blocks associated with the try block are checked to see whether they can catch the exception. Catch blocks typically specify exception types; if the type of the catch block is the same type as the exception, or a base class of the exception, the catch block can handle the method. For example:

static void TestCatch()

{

try

{

TestThrow();

}

catch (System.Exception ex)

{

System.Console.WriteLine(ex.ToString());

}

}