Exception Класс
Определение
Представляет ошибки, которые происходят во время выполнения приложения.Represents errors that occur during application execution.
public ref class Exception
public ref class Exception : System::Runtime::Serialization::ISerializable
public ref class Exception : System::Runtime::InteropServices::_Exception, System::Runtime::Serialization::ISerializable
public class Exception
public class Exception : System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public class Exception : System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public class Exception : System.Runtime.Serialization.ISerializable
type Exception = class
type Exception = class
interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
type Exception = class
interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Exception = class
interface ISerializable
interface _Exception
[<System.Serializable>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Exception = class
interface ISerializable
Public Class Exception
Public Class Exception
Implements ISerializable
Public Class Exception
Implements _Exception, ISerializable
- Наследование
-
Exception
- Производный
- Атрибуты
- Реализации
Примеры
В следующем примере показан catch
блок, определенный для обработки ArithmeticException ошибок.The following example demonstrates a catch
block that is defined to handle ArithmeticException errors. Этот catch
блок также перехватывает DivideByZeroException ошибки, так как DivideByZeroException является производным от ArithmeticException и не существует блока, catch
явно определенного для DivideByZeroException ошибок.This catch
block also catches DivideByZeroException errors, because DivideByZeroException derives from ArithmeticException and there is no catch
block explicitly defined for DivideByZeroException errors.
using namespace System;
int main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch ( ArithmeticException^ e )
{
Console::WriteLine( "ArithmeticException Handler: {0}", e );
}
catch ( Exception^ e )
{
Console::WriteLine( "Generic Exception Handler: {0}", e );
}
}
/*
This code example produces the following results:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at main()
*/
using System;
class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch (ArithmeticException e)
{
Console.WriteLine($"ArithmeticException Handler: {e}");
}
catch (Exception e)
{
Console.WriteLine($"Generic Exception Handler: {e}");
}
}
}
/*
This code example produces the following results:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at ExceptionTestClass.Main()
*/
Class ExceptionTestClass
Public Shared Sub Main()
Dim x As Integer = 0
Try
Dim y As Integer = 100 / x
Catch e As ArithmeticException
Console.WriteLine("ArithmeticException Handler: {0}", e.ToString())
Catch e As Exception
Console.WriteLine("Generic Exception Handler: {0}", e.ToString())
End Try
End Sub
End Class
'
'This code example produces the following results:
'
'ArithmeticException Handler: System.OverflowException: Arithmetic operation resulted in an overflow.
' at ExceptionTestClass.Main()
'
Комментарии
Этот класс является базовым классом для всех исключений.This class is the base class for all exceptions. При возникновении ошибки система или выполняемое в настоящее время приложение сообщает о нем, вызывая исключение, которое содержит сведения об ошибке.When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. После возникновения исключения оно обрабатывается приложением или обработчиком исключений по умолчанию.After an exception is thrown, it is handled by the application or by the default exception handler.
СодержаниеIn this section:
Ошибки и исключения Errors and exceptions
Блоки try/catch Try/catch blocks
Функции типов исключений Exception type features
Свойства класса Exception Exception class properties
Вопросы производительности Performance considerations
Повторное создание исключения Re-throwing an exception
Выбор стандартных исключений Choosing standard exceptions
Реализация пользовательских исключенийImplementing custom exceptions
Ошибки и исключенияErrors and exceptions
Ошибки времени выполнения могут возникать по разным причинам.Run-time errors can occur for a variety of reasons. Однако не все ошибки должны обрабатываться как исключения в коде.However, not all errors should be handled as exceptions in your code. Ниже приведены некоторые категории ошибок, которые могут возникать во время выполнения, и соответствующие способы реагирования на них.Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.
Ошибки использования.Usage errors. Ошибка использования представляет ошибку в логике программы, которая может привести к исключению.A usage error represents an error in program logic that can result in an exception. Однако эта ошибка должна быть решена не посредством обработки исключений, но путем изменения неисправного кода.However, the error should be addressed not through exception handling but by modifying the faulty code. Например, переопределение Object.Equals(Object) метода в следующем примере предполагает, что
obj
аргумент всегда должен иметь значение, отличное от NULL.For example, the override of the Object.Equals(Object) method in the following example assumes that theobj
argument must always be non-null.using System; public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { // This implementation contains an error in program logic: // It assumes that the obj argument is not null. Person p = (Person) obj; return this.Name.Equals(p.Name); } } public class Example { public static void Main() { Person p1 = new Person(); p1.Name = "John"; Person p2 = null; // The following throws a NullReferenceException. Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); } }
Public Class Person Private _name As String Public Property Name As String Get Return _name End Get Set _name = value End Set End Property Public Overrides Function Equals(obj As Object) As Boolean ' This implementation contains an error in program logic: ' It assumes that the obj argument is not null. Dim p As Person = CType(obj, Person) Return Me.Name.Equals(p.Name) End Function End Class Module Example Public Sub Main() Dim p1 As New Person() p1.Name = "John" Dim p2 As Person = Nothing ' The following throws a NullReferenceException. Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module
NullReferenceExceptionИсключение, которое возникает,
obj
Еслиnull
можно устранить, изменив исходный код, чтобы явно проверить наличие значения null перед вызовом Object.Equals переопределения, а затем повторной компиляцией.The NullReferenceException exception that results whenobj
isnull
can be eliminated by modifying the source code to explicitly test for null before calling the Object.Equals override and then re-compiling. В следующем примере содержится исправленный исходный код, обрабатывающийnull
аргумент.The following example contains the corrected source code that handles anull
argument.using System; public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { // This implementation handles a null obj argument. Person p = obj as Person; if (p == null) return false; else return this.Name.Equals(p.Name); } } public class Example { public static void Main() { Person p1 = new Person(); p1.Name = "John"; Person p2 = null; Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); } } // The example displays the following output: // p1 = p2: False
Public Class Person Private _name As String Public Property Name As String Get Return _name End Get Set _name = value End Set End Property Public Overrides Function Equals(obj As Object) As Boolean ' This implementation handles a null obj argument. Dim p As Person = TryCast(obj, Person) If p Is Nothing Then Return False Else Return Me.Name.Equals(p.Name) End If End Function End Class Module Example Public Sub Main() Dim p1 As New Person() p1.Name = "John" Dim p2 As Person = Nothing Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module ' The example displays the following output: ' p1 = p2: False
Вместо использования обработки исключений для ошибок использования можно использовать Debug.Assert метод для обнаружения ошибок использования в отладочных сборках и Trace.Assert метод для обнаружения ошибок использования в сборках отладки и выпуска.Instead of using exception handling for usage errors, you can use the Debug.Assert method to identify usage errors in debug builds, and the Trace.Assert method to identify usage errors in both debug and release builds. Дополнительные сведения см. в разделе Утверждения в управляемом коде.For more information, see Assertions in Managed Code.
Ошибки программы.Program errors. Ошибка программы — это ошибка во время выполнения, которую не всегда можно избежать путем написания кода без ошибок.A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.
В некоторых случаях ошибка программы может отражать ожидаемое или предполагаемое состояние ошибки.In some cases, a program error may reflect an expected or routine error condition. В этом случае может потребоваться избежать использования обработки исключений для устранения ошибок программы, а затем повторить операцию.In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. Например, если пользователь должен ввести дату в определенном формате, можно выполнить синтаксический анализ строки даты, вызвав DateTime.TryParseExact метод, который возвращает Boolean значение, указывающее, была ли операция анализа успешной, вместо использования DateTime.ParseExact метода, который создает FormatException исключение, если строка даты не может быть преобразована в DateTime значение.For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the DateTime.TryParseExact method, which returns a Boolean value that indicates whether the parse operation succeeded, instead of using the DateTime.ParseExact method, which throws a FormatException exception if the date string cannot be converted to a DateTime value. Аналогично, если пользователь пытается открыть несуществующий файл, можно сначала вызвать File.Exists метод, чтобы проверить, существует ли файл, и, если нет, запросить у пользователя, нужно ли ему создать его.Similarly, if a user tries to open a file that does not exist, you can first call the File.Exists method to check whether the file exists and, if it does not, prompt the user whether he or she wants to create it.
В других случаях ошибка программы отражает непредвиденное условие ошибки, которое может быть обработано в коде.In other cases, a program error reflects an unexpected error condition that can be handled in your code. Например, даже если проверено, что файл существует, он может быть удален до его открытия или поврежден.For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. В этом случае попытка открыть файл путем создания экземпляра StreamReader объекта или вызова Open метода может вызвать FileNotFoundException исключение.In that case, trying to open the file by instantiating a StreamReader object or calling the Open method may throw a FileNotFoundException exception. В таких случаях для восстановления после ошибки следует использовать обработку исключений.In these cases, you should use exception handling to recover from the error.
Сбои системы.System failures. Сбой системы — это ошибка времени выполнения, которая не может быть обработана программно понятным образом.A system failure is a run-time error that cannot be handled programmatically in a meaningful way. Например, любой метод может вызвать исключение, OutOfMemoryException Если среда CLR не может выделить дополнительную память.For example, any method can throw an OutOfMemoryException exception if the common language runtime is unable to allocate additional memory. Обычно системные сбои не обрабатываются с помощью обработки исключений.Ordinarily, system failures are not handled by using exception handling. Вместо этого можно использовать событие, например, AppDomain.UnhandledException и вызвать Environment.FailFast метод для регистрации сведений об исключениях и уведомить пользователя об ошибке до завершения работы приложения.Instead, you may be able to use an event such as AppDomain.UnhandledException and call the Environment.FailFast method to log exception information and notify the user of the failure before the application terminates.
Блоки try/catchTry/catch blocks
Среда CLR предоставляет модель обработки исключений, основанную на представлении исключений в виде объектов, а также разделении кода программы и кода обработки исключений на try
блоки и catch
блоки.The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into try
blocks and catch
blocks. Может существовать один или несколько catch
блоков, каждый из которых предназначен для обработки определенного типа исключений, или один блок, предназначенный для перехвата более конкретного исключения, чем у другого блока.There can be one or more catch
blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block.
Если приложение обрабатывает исключения, происходящие во время выполнения блока кода приложения, код должен быть помещен в try
оператор и называться try
блоком.If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try
statement and is called a try
block. Код приложения, обрабатывающий исключения, созданные try
блоком, помещается в catch
оператор и называется catch
блоком.Application code that handles exceptions thrown by a try
block is placed within a catch
statement and is called a catch
block. catch
С блоком связано ноль или более блоков try
, и каждый catch
блок включает фильтр типа, который определяет типы исключений, которые он обрабатывает.Zero or more catch
blocks are associated with a try
block, and each catch
block includes a type filter that determines the types of exceptions it handles.
Когда в блоке возникает исключение try
, система ищет связанные catch
блоки в том порядке, в котором они отображаются в коде приложения, пока не обнаружит catch
блок, обрабатывающий исключение.When an exception occurs in a try
block, the system searches the associated catch
blocks in the order they appear in application code, until it locates a catch
block that handles the exception. catch
Блок обрабатывает исключение типа T
, если фильтр типа блока catch указывает T
или любой тип, T
производный от.A catch
block handles an exception of type T
if the type filter of the catch block specifies T
or any type that T
derives from. Система прекратит поиск после того, как обнаружит первый catch
блок, обрабатывающий исключение.The system stops searching after it finds the first catch
block that handles the exception. По этой причине в коде приложения catch
блок, обрабатывающий тип, должен быть указан перед catch
блоком, обрабатывающим его базовые типы, как показано в примере, который следует за этим разделом.For this reason, in application code, a catch
block that handles a type must be specified before a catch
block that handles its base types, as demonstrated in the example that follows this section. Блок catch, дескрипторы которого System.Exception
указаны последними.A catch block that handles System.Exception
is specified last.
Если ни один из catch
блоков, связанных с текущим try
блоком, не обрабатывает исключение, а текущий try
блок вложен в другие try
блоки в текущем вызове, catch
Поиск осуществляется по блокам, связанным со следующим включающим try
блоком.If none of the catch
blocks associated with the current try
block handle the exception, and the current try
block is nested within other try
blocks in the current call, the catch
blocks associated with the next enclosing try
block are searched. Если catch
блок для исключения не найден, система выполняет поиск предыдущего уровня вложенности в текущем вызове.If no catch
block for the exception is found, the system searches previous nesting levels in the current call. Если catch
в текущем вызове не найдено ни одного блока для исключения, исключение передается вверх по стеку вызовов, а в предыдущем кадре стека выполняется поиск catch
блока, обрабатывающего исключение.If no catch
block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a catch
block that handles the exception. Поиск в стеке вызовов продолжится до тех пор, пока не будет обработано исключение или пока в стеке вызовов не будут существовать кадры.The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. Если начало стека вызовов достигается без поиска catch
блока, обрабатывающего исключение, обработчик исключений по умолчанию обрабатывает его и завершает работу приложения.If the top of the call stack is reached without finding a catch
block that handles the exception, the default exception handler handles it and the application terminates.
Функции типов исключенийException type features
Типы исключений поддерживают следующие функции.Exception types support the following features:
Понятный для человека текст, описывающий ошибку.Human-readable text that describes the error. При возникновении исключения среда выполнения предоставляет доступ к текстовому сообщению для информирования пользователя о характере ошибки и предложения действия для решения проблемы.When an exception occurs, the runtime makes a text message available to inform the user of the nature of the error and to suggest action to resolve the problem. Это текстовое сообщение хранится в Message свойстве объекта исключения.This text message is held in the Message property of the exception object. Во время создания объекта исключения можно передать в конструктор текстовую строку для описания сведений об этом конкретном исключении.During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. Если для конструктора не задан аргумент сообщения об ошибке, используется сообщение об ошибке по умолчанию.If no error message argument is supplied to the constructor, the default error message is used. Дополнительные сведения см. в описании свойства Message.For more information, see the Message property.
Состояние стека вызовов при возникновении исключения.The state of the call stack when the exception was thrown. StackTraceСвойство содержит трассировку стека, которую можно использовать для определения места возникновения ошибки в коде.The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code. В трассировке стека перечислены все вызываемые методы и номера строк в исходном файле, где выполняются вызовы.The stack trace lists all the called methods and the line numbers in the source file where the calls are made.
Свойства класса ExceptionException class properties
ExceptionКласс включает ряд свойств, помогающих определить расположение кода, тип, файл справки и причину исключения: StackTrace , InnerException , Message , HelpLink ,, HResult Source , TargetSite и Data .The Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.
Если между двумя или более исключениями существует связь с причинами, InnerException это свойство поддерживает эти сведения.When a causal relationship exists between two or more exceptions, the InnerException property maintains this information. Внешнее исключение создается в ответ на это внутреннее исключение.The outer exception is thrown in response to this inner exception. Код, обрабатывающий внешнее исключение, может использовать сведения из предыдущего внутреннего исключения для более адекватной обработки ошибки.The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Дополнительные сведения об исключении могут храниться в виде коллекции пар "ключ-значение" в Data свойстве.Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property.
Строка сообщения об ошибке, которая передается конструктору во время создания объекта исключения, должна быть локализована и может быть предоставлена из файла ресурсов с помощью ResourceManager класса.The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the ResourceManager class. Дополнительные сведения о локализованных ресурсах см. в разделах Создание вспомогательных сборок и Упаковка и развертывание ресурсов .For more information about localized resources, see the Creating Satellite Assemblies and Packaging and Deploying Resources topics.
Чтобы предоставить пользователю подробные сведения о причине возникновения исключения, HelpLink свойство может содержать URL-адрес (или URN) файла справки.To provide the user with extensive information about why the exception occurred, the HelpLink property can hold a URL (or URN) to a help file.
ExceptionКласс использует COR_E_EXCEPTION HRESULT, имеющий значение 0x80131500.The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.
Список начальных значений свойств для экземпляра Exception класса см. в разделе Exception конструкторы.For a list of initial property values for an instance of the Exception class, see the Exception constructors.
Вопросы производительностиPerformance considerations
Создание или обработка исключения требует значительного количества системных ресурсов и времени выполнения.Throwing or handling an exception consumes a significant amount of system resources and execution time. Вызывайте исключения только для обработки действительно неисключительных условий, а не для обработки прогнозируемых событий или управления потоком.Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. Например, в некоторых случаях, например при разработке библиотеки классов, разумно создать исключение, если аргумент метода является недопустимым, так как предполагается, что метод будет вызываться с допустимыми параметрами.For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. Недопустимый аргумент метода, если он не является результатом ошибки использования, означает, что возникла непредвиденная ошибка.An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. И наоборот, не вызывайте исключение, если ввод пользователя является недопустимым, так как вы можете рассчитывать, что пользователи иногда вводят недопустимые данные.Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Вместо этого предоставьте механизм повторных попыток, чтобы пользователи могли ввести допустимые входные данные.Instead, provide a retry mechanism so users can enter valid input. Кроме того, не следует использовать исключения для обработки ошибок использования.Nor should you use exceptions to handle usage errors. Вместо этого используйте утверждения для обнаружения и исправления ошибок использования.Instead, use assertions to identify and correct usage errors.
Кроме того, не вызывайте исключение, если достаточно кода возврата; не преобразуйте код возврата в исключение; и не перехватывают исключение, игнорируйте его, а затем продолжайте обработку.In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing.
Повторный вызов исключенияRe-throwing an exception
Во многих случаях обработчик исключений просто хочет передать исключение в вызывающий объект.In many cases, an exception handler simply wants to pass the exception on to the caller. Чаще всего это происходит в следующих случаях.This most often occurs in:
Библиотека классов, которая, в свою очередь, заключает вызовы методов в библиотеку классов платформа .NET Framework или другие библиотеки классов.A class library that in turn wraps calls to methods in the .NET Framework class library or other class libraries.
Приложение или библиотека, вызывающая неустранимое исключение.An application or library that encounters a fatal exception. Обработчик исключений может зарегистрировать исключение, а затем повторно создать исключение.The exception handler can log the exception and then re-throw the exception.
Для повторного создания исключения рекомендуется просто использовать инструкцию throw в C# и инструкцию throw в Visual Basic без включения выражения.The recommended way to re-throw an exception is to simply use the throw statement in C# and the Throw statement in Visual Basic without including an expression. Это гарантирует, что все сведения стека вызовов сохраняются при распространении исключения вызывающему объекту.This ensures that all call stack information is preserved when the exception is propagated to the caller. Это показано в следующем примере.The following example illustrates this. Метод расширения строки ( FindOccurrences
) заключает в оболочку один или несколько вызовов String.IndexOf(String, Int32) без проверки своих аргументов заранее.A string extension method, FindOccurrences
, wraps one or more calls to String.IndexOf(String, Int32) without validating its arguments beforehand.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public static class Library
{
public static int[] FindOccurrences(this String s, String f)
{
var indexes = new List<int>();
int currentIndex = 0;
try {
while (currentIndex >= 0 && currentIndex < s.Length) {
currentIndex = s.IndexOf(f, currentIndex);
if (currentIndex >= 0) {
indexes.Add(currentIndex);
currentIndex++;
}
}
}
catch (ArgumentNullException e) {
// Perform some action here, such as logging this exception.
throw;
}
return indexes.ToArray();
}
}
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Public Module Library
<Extension()>
Public Function FindOccurrences(s As String, f As String) As Integer()
Dim indexes As New List(Of Integer)
Dim currentIndex As Integer = 0
Try
Do While currentIndex >= 0 And currentIndex < s.Length
currentIndex = s.IndexOf(f, currentIndex)
If currentIndex >= 0 Then
indexes.Add(currentIndex)
currentIndex += 1
End If
Loop
Catch e As ArgumentNullException
' Perform some action here, such as logging this exception.
Throw
End Try
Return indexes.ToArray()
End Function
End Module
Затем вызывающий объект вызывается FindOccurrences
дважды.A caller then calls FindOccurrences
twice. Во втором вызове FindOccurrences
вызывающий объект передает в null
качестве строки поиска, в результате чего String.IndexOf(String, Int32) метод создает ArgumentNullException исключение.In the second call to FindOccurrences
, the caller passes a null
as the search string, which cases the String.IndexOf(String, Int32) method to throw an ArgumentNullException exception. Это исключение обрабатывается FindOccurrences
методом и передается обратно вызывающему объекту.This exception is handled by the FindOccurrences
method and passed back to the caller. Поскольку оператор throw используется без выражения, выходные данные в примере показывают, что стек вызовов сохранен.Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved.
public class Example
{
public static void Main()
{
String s = "It was a cold day when...";
int[] indexes = s.FindOccurrences("a");
ShowOccurrences(s, "a", indexes);
Console.WriteLine();
String toFind = null;
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine("Message:\n {0}\n", e.Message);
Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace);
}
}
private static void ShowOccurrences(String s, String toFind, int[] indexes)
{
Console.Write("'{0}' occurs at the following character positions: ",
toFind);
for (int ctr = 0; ctr < indexes.Length; ctr++)
Console.Write("{0}{1}", indexes[ctr],
ctr == indexes.Length - 1 ? "" : ", ");
Console.WriteLine();
}
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message:
// Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
Module Example
Public Sub Main()
Dim s As String = "It was a cold day when..."
Dim indexes() As Integer = s.FindOccurrences("a")
ShowOccurrences(s, "a", indexes)
Console.WriteLine()
Dim toFind As String = Nothing
Try
indexes = s.FindOccurrences(toFind)
ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name)
Console.WriteLine("Message:{0} {1}{0}", vbCrLf, e.Message)
Console.WriteLine("Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace)
End Try
End Sub
Private Sub ShowOccurrences(s As String, toFind As String, indexes As Integer())
Console.Write("'{0}' occurs at the following character positions: ",
toFind)
For ctr As Integer = 0 To indexes.Length - 1
Console.Write("{0}{1}", indexes(ctr),
If(ctr = indexes.Length - 1, "", ", "))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' 'a' occurs at the following character positions: 4, 7, 15
'
' An exception (ArgumentNullException) occurred.
' Message:
' Value cannot be null.
' Parameter name: value
'
' Stack Trace:
' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
' ngComparison comparisonType)
' at Library.FindOccurrences(String s, String f)
' at Example.Main()
Напротив, если исключение создается повторно с помощью методаIn contrast, if the exception is re-thrown by using the
throw e;
Throw e
, полный стек вызовов не сохраняется, и в примере создается следующий результат:statement, the full call stack is not preserved, and the example would generate the following output:
'a' occurs at the following character positions: 4, 7, 15
An exception (ArgumentNullException) occurred.
Message:
Value cannot be null.
Parameter name: value
Stack Trace:
at Library.FindOccurrences(String s, String f)
at Example.Main()
Немного более громоздкий альтернативой является вызов нового исключения и сохранение сведений стека вызовов исходного исключения во внутреннем исключении.A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. Затем вызывающий объект может использовать свойство нового исключения InnerException для получения кадра стека и других сведений об исходном исключении.The caller can then use the new exception's InnerException property to retrieve stack frame and other information about the original exception. В этом случае оператор Throw будет следующим:In this case, the throw statement is:
throw new ArgumentNullException("You must supply a search string.",
e);
Throw New ArgumentNullException("You must supply a search string.",
e)
Пользовательский код, обрабатывающий исключение, должен иметь представление о том, что InnerException свойство содержит сведения об исходном исключении, как показано в следующем обработчике исключений.The user code that handles the exception has to know that the InnerException property contains information about the original exception, as the following exception handler illustrates.
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine(" Message:\n{0}", e.Message);
Console.WriteLine(" Stack Trace:\n {0}", e.StackTrace);
Exception ie = e.InnerException;
if (ie != null) {
Console.WriteLine(" The Inner Exception:");
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name);
Console.WriteLine(" Message: {0}\n", ie.Message);
Console.WriteLine(" Stack Trace:\n {0}\n", ie.StackTrace);
}
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message: You must supply a search string.
//
// Stack Trace:
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
//
// The Inner Exception:
// Exception Name: ArgumentNullException
// Message: Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
Try
indexes = s.FindOccurrences(toFind)
ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name)
Console.WriteLine(" Message: {1}{0}", vbCrLf, e.Message)
Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace)
Dim ie As Exception = e.InnerException
If ie IsNot Nothing Then
Console.WriteLine(" The Inner Exception:")
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name)
Console.WriteLine(" Message: {1}{0}", vbCrLf, ie.Message)
Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, ie.StackTrace)
End If
End Try
' The example displays the following output:
' 'a' occurs at the following character positions: 4, 7, 15
'
' An exception (ArgumentNullException) occurred.
' Message: You must supply a search string.
'
' Stack Trace:
' at Library.FindOccurrences(String s, String f)
' at Example.Main()
'
' The Inner Exception:
' Exception Name: ArgumentNullException
' Message: Value cannot be null.
' Parameter name: value
'
' Stack Trace:
' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
' ngComparison comparisonType)
' at Library.FindOccurrences(String s, String f)
Выбор стандартных исключенийChoosing standard exceptions
Если необходимо создать исключение, часто можно использовать существующий тип исключения в платформа .NET Framework вместо реализации пользовательского исключения.When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. В этих двух условиях следует использовать стандартный тип исключений.You should use a standard exception type under these two conditions:
Создается исключение, вызванное ошибкой использования (то есть ошибкой в логике программы, выполняемой разработчиком, вызывающим метод).You are throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). Как правило, создается исключение, например,, ArgumentException ArgumentNullException InvalidOperationException или NotSupportedException .Typically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. Строка, предоставляемая конструктору объекта исключения при создании объекта исключения, должна описывать ошибку, чтобы разработчик мог ее исправить.The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. Дополнительные сведения см. в описании свойства Message.For more information, see the Message property.
Вы обрабатываете ошибку, которая может быть передана вызывающему объекту с существующим исключением платформа .NET Framework.You are handling an error that can be communicated to the caller with an existing .NET Framework exception. Рекомендуется создавать наиболее производное исключение.You should throw the most derived exception possible. Например, если метод требует, чтобы аргумент был допустимым членом типа перечисления, следует вызвать исключение InvalidEnumArgumentException (самый производный класс), а не ArgumentException .For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.
В следующей таблице перечислены распространенные типы исключений и условия их создания.The following table lists common exception types and the conditions under which you would throw them.
ИсключениеException | УсловиеCondition |
---|---|
ArgumentException | Непустой аргумент, передаваемый в метод, является недопустимым.A non-null argument that is passed to a method is invalid. |
ArgumentNullException | Аргумент, передаваемый в метод, — null .An argument that is passed to a method is null . |
ArgumentOutOfRangeException | Аргумент находится за пределами диапазона допустимых значений.An argument is outside the range of valid values. |
DirectoryNotFoundException | Недопустимая часть пути к каталогу.Part of a directory path is not valid. |
DivideByZeroException | Знаменатель в операции деления или целого числа Decimal равен нулю.The denominator in an integer or Decimal division operation is zero. |
DriveNotFoundException | Диск недоступен или не существует.A drive is unavailable or does not exist. |
FileNotFoundException | Файл не существует.A file does not exist. |
FormatException | Значение не находится в соответствующем формате для преобразования из строки методом преобразования, например Parse .A value is not in an appropriate format to be converted from a string by a conversion method such as Parse . |
IndexOutOfRangeException | Индекс находится за пределами границ массива или коллекции.An index is outside the bounds of an array or collection. |
InvalidOperationException | Вызов метода недопустим в текущем состоянии объекта.A method call is invalid in an object's current state. |
KeyNotFoundException | Не удается найти указанный ключ для доступа к элементу в коллекции.The specified key for accessing a member in a collection cannot be found. |
NotImplementedException | Метод или операция не реализованы.A method or operation is not implemented. |
NotSupportedException | Метод или операция не поддерживается.A method or operation is not supported. |
ObjectDisposedException | Операция выполняется над объектом, который был ликвидирован.An operation is performed on an object that has been disposed. |
OverflowException | Арифметическое, приведение или операция преобразования приводят к переполнению.An arithmetic, casting, or conversion operation results in an overflow. |
PathTooLongException | Длина пути или имени файла превышает максимальную длину, определенную системой.A path or file name exceeds the maximum system-defined length. |
PlatformNotSupportedException | Операция не поддерживается на текущей платформе.The operation is not supported on the current platform. |
RankException | В метод передается массив с неправильным числом измерений.An array with the wrong number of dimensions is passed to a method. |
TimeoutException | Срок действия интервала времени, выделенного для операции, истек.The time interval allotted to an operation has expired. |
UriFormatException | Используется недопустимый универсальный код ресурса (URI).An invalid Uniform Resource Identifier (URI) is used. |
Реализация пользовательских исключенийImplementing custom exceptions
В следующих случаях использование существующего исключения платформа .NET Framework для обработки состояния ошибки неадекватно:In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:
Если исключение отражает уникальную ошибку программы, которая не может быть сопоставлена с существующим исключением платформа .NET Framework.When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.
Если для исключения требуется обработка, которая отличается от обработки, подходящей для существующего исключения платформа .NET Framework, или исключение должно быть неоднозначной из аналогичного исключения.When the exception requires handling that is different from the handling that is appropriate for an existing .NET Framework exception, or the exception must be disambiguated from a similar exception. Например, если при ArgumentOutOfRangeException синтаксическом анализе числового представления строки, находящейся за пределами диапазона целевого целочисленного типа, выдается исключение, то не нужно использовать то же исключение для ошибки, полученной от вызывающей стороны, не предоставляющей соответствующие значения с ограничениями при вызове метода.For example, if you throw an ArgumentOutOfRangeException exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method.
ExceptionКласс является базовым классом всех исключений в платформа .NET Framework.The Exception class is the base class of all exceptions in the .NET Framework. Многие производные классы основываются на наследуемом поведении членов Exception класса; они не переопределяют члены Exception , а также не определяют уникальные члены.Many derived classes rely on the inherited behavior of the members of the Exception class; they do not override the members of Exception, nor do they define any unique members.
Определение собственного класса исключений:To define your own exception class:
Определите класс, наследующий от Exception .Define a class that inherits from Exception. При необходимости определите все уникальные элементы, необходимые для класса, чтобы предоставить дополнительные сведения об исключении.If necessary, define any unique members needed by your class to provide additional information about the exception. Например, ArgumentException класс включает ParamName свойство, указывающее имя параметра, аргумент которого вызывал исключение, а RegexMatchTimeoutException свойство содержит MatchTimeout свойство, указывающее интервал времени ожидания.For example, the ArgumentException class includes a ParamName property that specifies the name of the parameter whose argument caused the exception, and the RegexMatchTimeoutException property includes a MatchTimeout property that indicates the time-out interval.
При необходимости переопределите все унаследованные члены, функциональность которых требуется изменить или изменить.If necessary, override any inherited members whose functionality you want to change or modify. Обратите внимание, что большинство существующих производных классов Exception не переопределяют поведение наследуемых членов.Note that most existing derived classes of Exception do not override the behavior of inherited members.
Определите, является ли пользовательский объект исключения сериализуемым.Determine whether your custom exception object is serializable. Сериализация позволяет сохранять сведения об исключении и позволяет совместно использовать данные исключений сервером и прокси клиента в контексте удаленного взаимодействия.Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. Чтобы сделать объект исключения сериализуемым, пометьте его SerializableAttribute атрибутом.To make the exception object serializable, mark it with the SerializableAttribute attribute.
Определите конструкторы класса исключений.Define the constructors of your exception class. Как правило, классы исключений имеют один или несколько следующих конструкторов:Typically, exception classes have one or more of the following constructors:
Exception(), который использует значения по умолчанию для инициализации свойств нового объекта исключения.Exception(), which uses default values to initialize the properties of a new exception object.
Exception(String), который инициализирует новый объект исключения с указанным сообщением об ошибке.Exception(String), which initializes a new exception object with a specified error message.
Exception(String, Exception), который инициализирует новый объект исключения с указанным сообщением об ошибке и внутренним исключением.Exception(String, Exception), which initializes a new exception object with a specified error message and inner exception.
Exception(SerializationInfo, StreamingContext)— Это
protected
конструктор, инициализирующий новый объект исключения из сериализованных данных.Exception(SerializationInfo, StreamingContext), which is aprotected
constructor that initializes a new exception object from serialized data. Этот конструктор следует реализовать, если вы решили сделать объект исключения сериализуемым.You should implement this constructor if you've chosen to make your exception object serializable.
В следующем примере показано использование класса пользовательского исключения.The following example illustrates the use of a custom exception class. Он определяет NotPrimeException
исключение, которое создается, когда клиент пытается получить последовательность простых чисел, указав начальный номер, который не является простым.It defines a NotPrimeException
exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. Исключение определяет новое свойство, NonPrime
которое возвращает непростое число, которое привело к исключению.The exception defines a new property, NonPrime
, that returns the non-prime number that caused the exception. Помимо реализации защищенного конструктора без параметров и конструктора с SerializationInfo параметрами и StreamingContext для сериализации, NotPrimeException
класс определяет три дополнительных конструктора для поддержки NonPrime
Свойства.Besides implementing a protected parameterless constructor and a constructor with SerializationInfo and StreamingContext parameters for serialization, the NotPrimeException
class defines three additional constructors to support the NonPrime
property. Каждый конструктор вызывает конструктор базового класса, а также сохраняет значение непростого числа.Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. NotPrimeException
Класс также помечается SerializableAttribute атрибутом.The NotPrimeException
class is also marked with the SerializableAttribute attribute.
using System;
using System.Runtime.Serialization;
[Serializable()]
public class NotPrimeException : Exception
{
private int notAPrime;
protected NotPrimeException()
: base()
{ }
public NotPrimeException(int value) :
base(String.Format("{0} is not a prime number.", value))
{
notAPrime = value;
}
public NotPrimeException(int value, string message)
: base(message)
{
notAPrime = value;
}
public NotPrimeException(int value, string message, Exception innerException) :
base(message, innerException)
{
notAPrime = value;
}
protected NotPrimeException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{ }
public int NonPrime
{ get { return notAPrime; } }
}
Imports System.Runtime.Serialization
<Serializable()> _
Public Class NotPrimeException : Inherits Exception
Private notAPrime As Integer
Protected Sub New()
MyBase.New()
End Sub
Public Sub New(value As Integer)
MyBase.New(String.Format("{0} is not a prime number.", value))
notAPrime = value
End Sub
Public Sub New(value As Integer, message As String)
MyBase.New(message)
notAPrime = value
End Sub
Public Sub New(value As Integer, message As String, innerException As Exception)
MyBase.New(message, innerException)
notAPrime = value
End Sub
Protected Sub New(info As SerializationInfo,
context As StreamingContext)
MyBase.New(info, context)
End Sub
Public ReadOnly Property NonPrime As Integer
Get
Return notAPrime
End Get
End Property
End Class
PrimeNumberGenerator
Класс, показанный в следующем примере, использует Сиеве из ератоссенес для вычисления последовательности простых чисел из 2 в предел, заданный клиентом при вызове его конструктора класса.The PrimeNumberGenerator
class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. GetPrimesFrom
Метод возвращает все простые числа, которые больше или равны указанному нижнему пределу, но выдает исключение, NotPrimeException
Если нижний предел не является простым числом.The GetPrimesFrom
method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a NotPrimeException
if that lower limit is not a prime number.
using System;
using System.Collections.Generic;
[Serializable]
public class PrimeNumberGenerator
{
private const int START = 2;
private int maxUpperBound = 10000000;
private int upperBound;
private bool[] primeTable;
private List<int> primes = new List<int>();
public PrimeNumberGenerator(int upperBound)
{
if (upperBound > maxUpperBound)
{
string message = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound);
throw new ArgumentOutOfRangeException(message);
}
this.upperBound = upperBound;
// Create array and mark 0, 1 as not prime (True).
primeTable = new bool[upperBound + 1];
primeTable[0] = true;
primeTable[1] = true;
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound));
ctr++)
{
if (primeTable[ctr]) continue;
for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++)
if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true;
}
// Populate array with prime number information.
int index = START;
while (index != -1)
{
index = Array.FindIndex(primeTable, index, (flag) => !flag);
if (index >= 1)
{
primes.Add(index);
index++;
}
}
}
public int[] GetAllPrimes()
{
return primes.ToArray();
}
public int[] GetPrimesFrom(int prime)
{
int start = primes.FindIndex((value) => value == prime);
if (start < 0)
throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime));
else
return primes.FindAll((value) => value >= prime).ToArray();
}
}
Imports System.Collections.Generic
<Serializable()> Public Class PrimeNumberGenerator
Private Const START As Integer = 2
Private maxUpperBound As Integer = 10000000
Private upperBound As Integer
Private primeTable() As Boolean
Private primes As New List(Of Integer)
Public Sub New(upperBound As Integer)
If upperBound > maxUpperBound Then
Dim message As String = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound)
Throw New ArgumentOutOfRangeException(message)
End If
Me.upperBound = upperBound
' Create array and mark 0, 1 as not prime (True).
ReDim primeTable(upperBound)
primeTable(0) = True
primeTable(1) = True
' Use Sieve of Eratosthenes to determine prime numbers.
For ctr As Integer = START To CInt(Math.Ceiling(Math.Sqrt(upperBound)))
If primeTable(ctr) Then Continue For
For multiplier As Integer = ctr To CInt(upperBound \ ctr)
If ctr * multiplier <= upperBound Then primeTable(ctr * multiplier) = True
Next
Next
' Populate array with prime number information.
Dim index As Integer = START
Do While index <> -1
index = Array.FindIndex(primeTable, index, Function(flag)
Return Not flag
End Function)
If index >= 1 Then
primes.Add(index)
index += 1
End If
Loop
End Sub
Public Function GetAllPrimes() As Integer()
Return primes.ToArray()
End Function
Public Function GetPrimesFrom(prime As Integer) As Integer()
Dim start As Integer = primes.FindIndex(Function(value)
Return value = prime
End Function)
If start < 0 Then
Throw New NotPrimeException(prime, String.Format("{0} is not a prime number.", prime))
Else
Return primes.FindAll(Function(value)
Return value >= prime
End Function).ToArray()
End If
End Function
End Class
В следующем примере выполняется два вызова GetPrimesFrom
метода с непростыми числами, один из которых пересекают границы домена приложения.The following example makes two calls to the GetPrimesFrom
method with non-prime numbers, one of which crosses application domain boundaries. В обоих случаях исключение вызывается и успешно обрабатывается в клиентском коде.In both cases, the exception is thrown and successfully handled in client code.
using System;
using System.Reflection;
class Example
{
public static void Main()
{
int limit = 10000000;
PrimeNumberGenerator primes = new PrimeNumberGenerator(limit);
int start = 1000001;
try
{
int[] values = primes.GetPrimesFrom(start);
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit);
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
AppDomain domain = AppDomain.CreateDomain("Domain2");
PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap(
typeof(Example).Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
new object[] { 1000000 }, null, null);
try
{
start = 100;
Console.WriteLine(gen.GetPrimesFrom(start));
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
}
}
Imports System.Reflection
Module Example
Sub Main()
Dim limit As Integer = 10000000
Dim primes As New PrimeNumberGenerator(limit)
Dim start As Integer = 1000001
Try
Dim values() As Integer = primes.GetPrimesFrom(start)
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit)
Catch e As NotPrimeException
Console.WriteLine("{0} is not prime", e.NonPrime)
Console.WriteLine(e)
Console.WriteLine("--------")
End Try
Dim domain As AppDomain = AppDomain.CreateDomain("Domain2")
Dim gen As PrimeNumberGenerator = domain.CreateInstanceAndUnwrap(
GetType(Example).Assembly.FullName,
"PrimeNumberGenerator", True,
BindingFlags.Default, Nothing,
{1000000}, Nothing, Nothing)
Try
start = 100
Console.WriteLine(gen.GetPrimesFrom(start))
Catch e As NotPrimeException
Console.WriteLine("{0} is not prime", e.NonPrime)
Console.WriteLine(e)
Console.WriteLine("--------")
End Try
End Sub
End Module
' The example displays the following output:
' 1000001 is not prime
' NotPrimeException: 1000001 is not a prime number.
' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
' at Example.Main()
' --------
' 100 is not prime
' NotPrimeException: 100 is not a prime number.
' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
' at Example.Main()
' --------
среда выполнения Windows и .NET Framework 4.5.1.NET Framework 4.5.1Windows Runtime and .NET Framework 4.5.1.NET Framework 4.5.1
В .NET для приложений Магазина Windows 8.x.NET for Windows 8.x Store apps для Windows 8Windows 8 некоторые сведения об исключении обычно теряются при распространении исключения через кадры стека non-.NET Framework.In .NET для приложений Магазина Windows 8.x.NET for Windows 8.x Store apps for Windows 8Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. Начиная с версии .NET Framework 4.5.1.NET Framework 4.5.1 и Windows 8.1Windows 8.1 Среда CLR по-своему использует исходный Exception объект, который был создан, если это исключение не было изменено в кадре стека non-.NET Framework.Starting with the .NET Framework 4.5.1.NET Framework 4.5.1 and Windows 8.1Windows 8.1, the common language runtime continues to use the original Exception object that was thrown unless that exception was modified in a non-.NET Framework stack frame.
Конструкторы
Exception() |
Инициализирует новый экземпляр класса Exception.Initializes a new instance of the Exception class. |
Exception(SerializationInfo, StreamingContext) |
Инициализирует новый экземпляр класса Exception с сериализованными данными.Initializes a new instance of the Exception class with serialized data. |
Exception(String) |
Инициализирует новый экземпляр класса Exception с указанным сообщением об ошибке.Initializes a new instance of the Exception class with a specified error message. |
Exception(String, Exception) |
Инициализирует новый экземпляр класса Exception указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее данное исключение.Initializes a new instance of the Exception class with a specified error message and a reference to the inner exception that is the cause of this exception. |
Свойства
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 |
Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. |
InnerException |
Возвращает экземпляр класса Exception, который вызвал текущее исключение.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 |
Получает строковое представление непосредственных кадров в стеке вызова.Gets a string representation of the immediate frames on the call stack. |
TargetSite |
Возвращает метод, создавший текущее исключение.Gets the method that throws the current exception. |
Методы
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GetBaseException() |
При переопределении в производном классе возвращает исключение Exception, которое является первопричиной одного или нескольких последующих исключений.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. |
GetHashCode() |
Служит хэш-функцией по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetObjectData(SerializationInfo, StreamingContext) |
При переопределении в производном классе задает объект SerializationInfo со сведениями об исключении.When overridden in a derived class, sets the SerializationInfo with information about the exception. |
GetType() |
Возвращает тип среды выполнения текущего экземпляра.Gets the runtime type of the current instance. |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
ToString() |
Создает и возвращает строковое представление текущего исключения.Creates and returns a string representation of the current exception. |
События
SerializeObjectState |
Возникает, когда исключение сериализовано для создания объекта состояния исключения, содержащего сериализованные данные об исключении.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. |