Exception Klasse
Definition
Stellt Fehler dar, die bei der Anwendungsausführung auftreten.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
- Vererbung
-
Exception
- Abgeleitet
- Attribute
- Implementiert
Beispiele
Im folgenden Beispiel wird ein- catch
Block veranschaulicht, der zum Behandeln von Fehlern definiert ist ArithmeticException .The following example demonstrates a catch
block that is defined to handle ArithmeticException errors. Dieser catch
Block fängt auch DivideByZeroException Fehler ab, da DivideByZeroException von abgeleitet ArithmeticException ist und kein catch
Block explizit für Fehler definiert ist 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()
'
Hinweise
Diese Klasse ist die Basisklasse für alle Ausnahmen.This class is the base class for all exceptions. Wenn ein Fehler auftritt, meldet das System oder die aktuell ausgeführte Anwendung Sie durch Auslösen einer Ausnahme, die Informationen über den Fehler enthält.When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. Nachdem eine Ausnahme ausgelöst wurde, wird Sie von der Anwendung oder vom Standard Ausnahmehandler behandelt.After an exception is thrown, it is handled by the application or by the default exception handler.
Inhalt dieses Abschnitts:In this section:
Fehler und Ausnahmen Errors and exceptions
Try/catch-Blöcke Try/catch blocks
Ausnahmetyp Features Exception type features
Eigenschaften der Ausnahme Klasse Exception class properties
Überlegungen zur Leistung Performance considerations
Erneutes Auslösen einer Ausnahme Re-throwing an exception
Auswählen von Standard Ausnahmen Choosing standard exceptions
Implementieren von benutzerdefinierten AusnahmenImplementing custom exceptions
Fehler und AusnahmenErrors and exceptions
Laufzeitfehler können aus einer Vielzahl von Gründen auftreten.Run-time errors can occur for a variety of reasons. Allerdings sollten nicht alle Fehler im Code als Ausnahmen behandelt werden.However, not all errors should be handled as exceptions in your code. Im folgenden finden Sie einige Fehlerkategorien, die zur Laufzeit auftreten können, sowie die entsprechenden Möglichkeiten, um darauf zu reagieren.Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.
Verwendungs Fehler.Usage errors. Ein Verwendungs Fehler stellt einen Fehler in der Programmlogik dar, der zu einer Ausnahme führen kann.A usage error represents an error in program logic that can result in an exception. Der Fehler sollte jedoch nicht durch die Ausnahmebehandlung behoben werden, sondern durch Ändern des fehlerhaften Codes.However, the error should be addressed not through exception handling but by modifying the faulty code. Beim Überschreiben der- Object.Equals(Object) Methode im folgenden Beispiel wird z. b. davon ausgegangen, dass das
obj
-Argument immer ungleich NULL sein muss.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
Die NullReferenceException Ausnahme, die ergibt, wenn der
obj
null
-Wert gelöscht werden kann, indem der Quellcode so geändert wird, dass er vor dem Aufrufen der Object.Equals außer Kraft Setzung explizit überprüft und anschließend erneut kompiliert wird.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. Das folgende Beispiel enthält den korrigierten Quellcode, der ein-null
Argument behandelt.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
Anstelle der Ausnahmebehandlung bei Verwendungs Fehlern können Sie mithilfe der Debug.Assert -Methode Verwendungs Fehler in Debugbuilds identifizieren und die- Trace.Assert Methode zum Identifizieren von Verwendungs Fehlern in Debug-und Releasebuilds verwenden.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. Weitere Informationen finden Sie unter Assertionen in verwaltetem Code.For more information, see Assertions in Managed Code.
Programmfehler.Program errors. Ein Programmfehler ist ein Laufzeitfehler, der nicht zwangsläufig vermieden werden kann, indem fehlerfreier Code geschrieben wird.A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.
In einigen Fällen kann ein Programmfehler eine erwartete oder routinemäßige Fehlerbedingung widerspiegeln.In some cases, a program error may reflect an expected or routine error condition. In diesem Fall sollten Sie die Verwendung der Ausnahmebehandlung bei der Behandlung des Programmfehlers vermeiden und stattdessen den Vorgang wiederholen.In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. Wenn der Benutzer beispielsweise erwartet, dass ein Datum in einem bestimmten Format eingegeben wird, können Sie die Datums Zeichenfolge analysieren, indem Sie die- DateTime.TryParseExact Methode aufrufen, die einen Wert zurückgibt, der Boolean angibt, ob der Analyse Vorgang erfolgreich war, anstatt die- DateTime.ParseExact Methode zu verwenden, die eine-Ausnahme auslöst, FormatException Wenn die Datums Zeichenfolge nicht in einen-Wert konvertiert werden kann 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. Wenn ein Benutzer versucht, eine Datei zu öffnen, die nicht vorhanden ist, können Sie zuerst die-Methode aufzurufen, File.Exists um zu überprüfen, ob die Datei vorhanden ist. wenn dies nicht der Fall ist, können Sie den Benutzer auffordern, ihn zu erstellen.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 anderen Fällen gibt ein Programmfehler eine unerwartete Fehlerbedingung wider, die im Code behandelt werden kann.In other cases, a program error reflects an unexpected error condition that can be handled in your code. Wenn Sie z. b. geprüft haben, um sicherzustellen, dass eine Datei vorhanden ist, wird Sie möglicherweise gelöscht, bevor Sie Sie öffnen können, oder Sie ist möglicherweise beschädigt.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. Wenn Sie versuchen, die Datei zu öffnen, indem Sie ein-Objekt instanziieren StreamReader oder die-Methode aufrufen, Open kann eine-Ausnahme ausgelöst werden 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 diesen Fällen sollten Sie die Ausnahmebehandlung verwenden, um nach dem Fehler eine Wiederherstellung durchführen zu können.In these cases, you should use exception handling to recover from the error.
System Fehler.System failures. Ein Systemfehler ist ein Laufzeitfehler, der nicht Programm gesteuert auf sinnvolle Weise behandelt werden kann.A system failure is a run-time error that cannot be handled programmatically in a meaningful way. Beispielsweise kann jede Methode eine Ausnahme auslösen, OutOfMemoryException Wenn die Common Language Runtime keinen zusätzlichen Arbeitsspeicher zuordnen kann.For example, any method can throw an OutOfMemoryException exception if the common language runtime is unable to allocate additional memory. Normalerweise werden Systemfehler nicht mithilfe der Ausnahmebehandlung behandelt.Ordinarily, system failures are not handled by using exception handling. Stattdessen können Sie ein Ereignis wie z. b. verwenden AppDomain.UnhandledException und die- Environment.FailFast Methode zum Protokollieren von Ausnahme Informationen auffordern und den Benutzer über den Fehler benachrichtigen, bevor die Anwendung beendet wird.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/catch-BlöckeTry/catch blocks
Der Common Language Runtime stellt ein Modell für die Ausnahmebehandlung bereit, das auf der Darstellung von Ausnahmen als-Objekte und der Trennung von Programmcode und Ausnahme Behandlungs Code in try
Blöcke und catch
Blöcke basiert.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. Es können ein oder mehrere Blöcke vorhanden sein catch
, die jeweils für die Behandlung eines bestimmten Ausnahme Typs entworfen wurden, oder einen Block, der eine spezifischere Ausnahme als einen anderen Block abfangen soll.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.
Wenn eine Anwendung Ausnahmen behandelt, die während der Ausführung eines Blocks von Anwendungscode auftreten, muss der Code in einer try
-Anweisung abgelegt und als Block bezeichnet werden 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. Anwendungscode, der von einem-Block ausgelöste Ausnahmen behandelt, try
wird in einer catch
-Anweisung abgelegt und als catch
Block bezeichnet.Application code that handles exceptions thrown by a try
block is placed within a catch
statement and is called a catch
block. 0 (null) oder mehr catch
Blöcke sind einem try
-Block zugeordnet, und jeder- catch
Block enthält einen Typfilter, der die Typen der von ihm verarbeiteten Ausnahmen bestimmt.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.
Wenn eine Ausnahme in einem- try
Block auftritt, durchsucht das System die zugeordneten catch
Blöcke in der Reihenfolge, in der Sie im Anwendungscode angezeigt werden, bis ein-Block gesucht wird, catch
der die Ausnahme behandelt.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. Ein- catch
Block behandelt eine Ausnahme vom Typ T
, wenn der Typfilter des catch-Blocks angibt T
, oder einen beliebigen Typ, der T
von abgeleitet wird.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. Das System beendet die Suche, nachdem der erste catch
Block gefunden wurde, der die Ausnahme behandelt.The system stops searching after it finds the first catch
block that handles the exception. Aus diesem Grund muss im Anwendungscode ein- catch
Block, der einen-Typ behandelt, vor einem-Block angegeben werden, der catch
seine Basis Typen behandelt, wie in dem Beispiel veranschaulicht, das diesem Abschnitt folgt.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. Ein catch-Block, der behandelt, System.Exception
wird zuletzt angegeben.A catch block that handles System.Exception
is specified last.
Wenn keiner der catch
Blöcke, die dem aktuellen Block zugeordnet sind try
, die Ausnahme behandelt und der aktuelle try
Block innerhalb anderer Blöcke im aktuellen-Befehl geschachtelt ist try
, catch
werden die Blöcke durchsucht, die dem nächsten einschließenden try
Block zugeordnet sind.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. Wenn kein catch
Block für die Ausnahme gefunden wird, durchsucht das System vorherige Schachtelungs Ebenen im aktuellen-Befehl.If no catch
block for the exception is found, the system searches previous nesting levels in the current call. Wenn im aktuellen-Befehl kein catch
Block für die Ausnahme gefunden wird, wird die Ausnahme in der-aufrufsstapel nach oben und der vorherige Stapel Rahmen durchsucht nach einem-Block, der catch
die Ausnahme behandelt.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. Die Suche der-Aufrufliste wird fortgesetzt, bis die Ausnahme behandelt wird, oder bis keine Frames mehr in der aufrufsliste vorhanden sind.The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. Wenn der obere Rand der-Auflistung erreicht wird, ohne einen-Block zu finden catch
, der die Ausnahme behandelt, verarbeitet der Standard Ausnahmehandler diesen, und die Anwendung wird beendet.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.
Ausnahmetyp FeaturesException type features
Ausnahme Typen unterstützen die folgenden Funktionen:Exception types support the following features:
Von Menschen lesbarer Text, der den Fehler beschreibt.Human-readable text that describes the error. Wenn eine Ausnahme auftritt, stellt die Laufzeit eine Textnachricht zur Verfügung, um den Benutzer über die Art des Fehlers zu informieren und Aktionen vorzuschlagen, um das Problem zu beheben.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. Diese Textnachricht wird in der- Message Eigenschaft des Ausnahme Objekts gespeichert.This text message is held in the Message property of the exception object. Während der Erstellung des Ausnahme Objekts können Sie eine Text Zeichenfolge an den Konstruktor übergeben, um die Details dieser Ausnahme zu beschreiben.During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. Wenn kein Fehlermeldungs Argument an den Konstruktor übergeben wird, wird die Standard Fehlermeldung verwendet.If no error message argument is supplied to the constructor, the default error message is used. Weitere Informationen finden Sie in den Ausführungen zur Message-Eigenschaft.For more information, see the Message property.
Der Zustand der aufrufsstapel, als die Ausnahme ausgelöst wurde.The state of the call stack when the exception was thrown. Die- StackTrace Eigenschaft enthält eine Stapel Überwachung, die verwendet werden kann, um zu bestimmen, wo der Fehler im Code auftritt.The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code. Die Stapel Überwachung listet alle aufgerufenen Methoden und die Zeilennummern in der Quelldatei auf, in der die Aufrufe durchgeführt werden.The stack trace lists all the called methods and the line numbers in the source file where the calls are made.
Eigenschaften der Ausnahme KlasseException class properties
Die Exception -Klasse enthält eine Reihe von Eigenschaften, mit deren Hilfe der Code Speicherort, der Typ, die Hilfedatei und der Grund für die Ausnahme identifiziert werden können: StackTrace , InnerException , Message , HelpLink , HResult , Source , TargetSite und 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.
Wenn eine kausale Beziehung zwischen mindestens zwei Ausnahmen besteht, InnerException behält die Eigenschaft diese Informationen bei.When a causal relationship exists between two or more exceptions, the InnerException property maintains this information. Die äußere Ausnahme wird als Reaktion auf diese innere Ausnahme ausgelöst.The outer exception is thrown in response to this inner exception. Der Code, der die äußere Ausnahme behandelt, kann die Informationen aus der früheren inneren Ausnahme verwenden, um den Fehler besser zu behandeln.The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Ergänzende Informationen zur Ausnahme können als eine Auflistung von Schlüssel-Wert-Paaren in der-Eigenschaft gespeichert werden Data .Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property.
Die Fehlermeldungs Zeichenfolge, die während der Erstellung des Ausnahme Objekts an den-Konstruktor übergeben wird, muss lokalisiert werden und kann mithilfe der-Klasse aus einer Ressourcen Datei bereitgestellt werden 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. Weitere Informationen zu lokalisierten Ressourcen finden Sie in den Themen Erstellen von Satellitenassemblys und Verpacken und Bereitstellen von Ressourcen.For more information about localized resources, see the Creating Satellite Assemblies and Packaging and Deploying Resources topics.
Die- HelpLink Eigenschaft kann eine URL (oder einen URN) zu einer Hilfedatei enthalten, um dem Benutzer umfassende Informationen über die Ursache der Ausnahme bereitzustellen.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.
Die- Exception Klasse verwendet die HRESULT-COR_E_EXCEPTION, die den Wert 0x80131500 aufweist.The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.
Eine Liste der anfänglichen Eigenschaftswerte für eine Instanz der- Exception Klasse finden Sie unter den- Exception Konstruktoren.For a list of initial property values for an instance of the Exception class, see the Exception constructors.
Überlegungen zur LeistungPerformance considerations
Das auslösen oder behandeln einer Ausnahme beansprucht eine beträchtliche Menge an Systemressourcen und Ausführungszeit.Throwing or handling an exception consumes a significant amount of system resources and execution time. Lösen Sie Ausnahmen nur aus, um wirklich außergewöhnliche Bedingungen zu behandeln, nicht zur Behandlung vorhersag barer Ereignisse oder Fluss Steuerung.Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. In einigen Fällen, z. b. bei der Entwicklung einer Klassenbibliothek, ist es sinnvoll, eine Ausnahme auszulösen, wenn ein Methoden Argument ungültig ist, da Sie davon ausgehen, dass Ihre Methode mit gültigen Parametern aufgerufen wird.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. Ein ungültiges Methoden Argument, wenn es nicht das Ergebnis eines Verwendungs Fehlers ist, bedeutet, dass etwas Außergewöhnliches aufgetreten ist.An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. Im Gegensatz dazu lösen Sie keine Ausnahme aus, wenn die Benutzereingabe ungültig ist, da Sie davon ausgehen können, dass Benutzer gelegentlich ungültige Daten eingeben.Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Stellen Sie stattdessen einen Wiederholungs Mechanismus bereit, damit Benutzer gültige Eingaben eingeben können.Instead, provide a retry mechanism so users can enter valid input. Sie sollten auch keine Ausnahmen verwenden, um Verwendungs Fehler zu behandeln.Nor should you use exceptions to handle usage errors. Verwenden Sie stattdessen Assertionen, um Verwendungs Fehler zu identifizieren und zu korrigieren.Instead, use assertions to identify and correct usage errors.
Außerdem sollten Sie keine Ausnahme auslösen, wenn ein Rückgabecode ausreichend ist. Konvertieren Sie keinen Rückgabecode in eine Ausnahme. und fangen eine Ausnahme nicht regelmäßig ab, ignorieren Sie und setzen die Verarbeitung fort.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.
Erneutes Auslösen einer AusnahmeRe-throwing an exception
In vielen Fällen möchte ein Ausnahmehandler einfach die Ausnahme an den Aufrufer übergeben.In many cases, an exception handler simply wants to pass the exception on to the caller. Dies tritt am häufigsten in folgenden Fällen auf:This most often occurs in:
Eine Klassenbibliothek, die wiederum Aufrufe von Methoden in der .NET Framework-Klassenbibliothek oder anderen Klassenbibliotheken umschließt.A class library that in turn wraps calls to methods in the .NET Framework class library or other class libraries.
Eine Anwendung oder Bibliothek, auf die eine schwerwiegende Ausnahme stößt.An application or library that encounters a fatal exception. Der Ausnahmehandler kann die Ausnahme protokollieren und die Ausnahme dann erneut auslösen.The exception handler can log the exception and then re-throw the exception.
Die empfohlene Methode, eine Ausnahme erneut auszulösen, besteht darin, einfach die throw -Anweisung in c# und die throw -Anweisung in Visual Basic zu verwenden, ohne einen Ausdruck einzubeziehen.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. Dadurch wird sichergestellt, dass alle Aufruf Listen Informationen beibehalten werden, wenn die Ausnahme an den Aufrufer weitergegeben wird.This ensures that all call stack information is preserved when the exception is propagated to the caller. Dies wird anhand des folgenden Beispiels veranschaulicht.The following example illustrates this. Eine Zeichen folgen Erweiterungsmethode,, umschließt FindOccurrences
einen oder mehrere Aufrufe von, String.IndexOf(String, Int32) ohne dass die Argumente vorher überprüft werden.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
Ein Aufrufer ruft dann FindOccurrences
zweimal auf.A caller then calls FindOccurrences
twice. Im zweiten Aufruf von übergibt der Aufrufer FindOccurrences
einen null
als Such Zeichenfolge, in der die- String.IndexOf(String, Int32) Methode eine ArgumentNullException Ausnahme auslöst.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. Diese Ausnahme wird von der FindOccurrences
-Methode behandelt und an den Aufrufer zurückgegeben.This exception is handled by the FindOccurrences
method and passed back to the caller. Da die throw-Anweisung ohne Ausdruck verwendet wird, zeigt die Ausgabe des Beispiels, dass die-Anweisung beibehalten wird.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()
Im Gegensatz dazu wird die Ausnahme, wenn die Ausnahme erneut ausgelöst wird, mithilfe desIn contrast, if the exception is re-thrown by using the
throw e;
Throw e
-Anweisung, die vollständige-Aufrufliste wird nicht beibehalten, und im Beispiel wird die folgende Ausgabe generiert: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()
Eine etwas mühlichere Alternative besteht darin, eine neue Ausnahme auszulösen und die aufrufstackinformationen der ursprünglichen Ausnahme in einer inneren Ausnahme beizubehalten.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. Der Aufrufer kann dann die-Eigenschaft der neuen Ausnahme verwenden InnerException , um Stapel Rahmen und andere Informationen zur ursprünglichen Ausnahme abzurufen.The caller can then use the new exception's InnerException property to retrieve stack frame and other information about the original exception. In diesem Fall lautet die throw-Anweisung wie folgt: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)
Der Benutzercode, der die Ausnahme behandelt, muss wissen, dass die- InnerException Eigenschaft Informationen zur ursprünglichen Ausnahme enthält, wie der folgende Ausnahmehandler veranschaulicht.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)
Auswählen von Standard AusnahmenChoosing standard exceptions
Wenn Sie eine Ausnahme auslösen müssen, können Sie in der .NET Framework häufig einen vorhandenen Ausnahmetyp verwenden, anstatt eine benutzerdefinierte Ausnahme zu implementieren.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. Sie sollten unter diesen beiden Bedingungen einen Standard Ausnahmetyp verwenden:You should use a standard exception type under these two conditions:
Sie lösen eine Ausnahme aus, die durch einen Verwendungs Fehler verursacht wird (d. h. durch einen Fehler in der Programmlogik des Entwicklers, der die-Methode aufgerufen hat).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). In der Regel lösen Sie eine Ausnahme aus ArgumentException , z ArgumentNullException . b.,, InvalidOperationException oder NotSupportedException .Typically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. Die Zeichenfolge, die Sie für den Konstruktor des Ausnahme Objekts angeben, wenn Sie das Ausnahme Objekt instanziieren, sollte den Fehler beschreiben, damit er vom Entwickler behoben werden kann.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. Weitere Informationen finden Sie in den Ausführungen zur Message-Eigenschaft.For more information, see the Message property.
Sie behandeln einen Fehler, der dem Aufrufer über eine vorhandene .NET Framework Ausnahme mitgeteilt werden kann.You are handling an error that can be communicated to the caller with an existing .NET Framework exception. Sie sollten die am meisten abgeleitete Ausnahme auslösen.You should throw the most derived exception possible. Wenn z. b. eine Methode erfordert, dass ein Argument ein gültiger Member eines Enumerationstyps ist, sollten Sie eine InvalidEnumArgumentException (die am meisten abgeleitete Klasse) anstelle eines auslösen 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.
In der folgenden Tabelle sind allgemeine Ausnahme Typen und die Bedingungen aufgeführt, unter denen Sie ausgelöst werden.The following table lists common exception types and the conditions under which you would throw them.
AusnahmeException | BedingungCondition |
---|---|
ArgumentException | Ein nicht-NULL-Argument, das an eine Methode übermittelt wird, ist ungültig.A non-null argument that is passed to a method is invalid. |
ArgumentNullException | Ein Argument, das an eine Methode übermittelt wird, ist null .An argument that is passed to a method is null . |
ArgumentOutOfRangeException | Ein Argument liegt außerhalb des Bereichs gültiger Werte.An argument is outside the range of valid values. |
DirectoryNotFoundException | Ein Teil des Verzeichnis Pfads ist ungültig.Part of a directory path is not valid. |
DivideByZeroException | Der Nenner in einem Integer-oder Decimal Divisions Vorgang ist 0 (null).The denominator in an integer or Decimal division operation is zero. |
DriveNotFoundException | Ein Laufwerk ist nicht verfügbar oder nicht vorhanden.A drive is unavailable or does not exist. |
FileNotFoundException | Eine Datei ist nicht vorhanden.A file does not exist. |
FormatException | Ein Wert liegt nicht in einem geeigneten Format vor, das von einer Zeichenfolge konvertiert werden soll, z Parse . b..A value is not in an appropriate format to be converted from a string by a conversion method such as Parse . |
IndexOutOfRangeException | Ein Index liegt außerhalb der Grenzen eines Arrays oder einer Auflistung.An index is outside the bounds of an array or collection. |
InvalidOperationException | Ein Methoden Aufrufwert ist im aktuellen Zustand eines Objekts ungültig.A method call is invalid in an object's current state. |
KeyNotFoundException | Der angegebene Schlüssel für den Zugriff auf einen Member in einer Auflistung wurde nicht gefunden.The specified key for accessing a member in a collection cannot be found. |
NotImplementedException | Eine Methode oder ein Vorgang ist nicht implementiert.A method or operation is not implemented. |
NotSupportedException | Eine Methode oder ein Vorgang wird nicht unterstützt.A method or operation is not supported. |
ObjectDisposedException | Für ein Objekt, das verworfen wurde, wird ein Vorgang ausgeführt.An operation is performed on an object that has been disposed. |
OverflowException | Ein arithmetischer Vorgang, ein Umwandlungs-oder Konvertierungs Vorgang führt zu einem Überlauf.An arithmetic, casting, or conversion operation results in an overflow. |
PathTooLongException | Ein Pfad-oder Dateiname überschreitet die maximale System definierte Länge.A path or file name exceeds the maximum system-defined length. |
PlatformNotSupportedException | Der Vorgang wird auf der aktuellen Plattform nicht unterstützt.The operation is not supported on the current platform. |
RankException | Ein Array mit der falschen Anzahl von Dimensionen wird an eine-Methode übermittelt.An array with the wrong number of dimensions is passed to a method. |
TimeoutException | Das für einen Vorgang zugewiesene Zeitintervall ist abgelaufen.The time interval allotted to an operation has expired. |
UriFormatException | Ein ungültiger Uniform Resource Identifier (URI) wird verwendet.An invalid Uniform Resource Identifier (URI) is used. |
Implementieren von benutzerdefinierten AusnahmenImplementing custom exceptions
In den folgenden Fällen ist die Verwendung einer vorhandenen .NET Framework Ausnahme zur Behandlung eines Fehler Zustands nicht ausreichend:In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:
Wenn die Ausnahme einen eindeutigen Programmfehler widerspiegelt, der einer vorhandenen .NET Framework Ausnahme nicht zugeordnet werden kann.When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.
Wenn die Ausnahme behandelt werden muss, die sich von der Behandlung unterscheidet, die für eine vorhandene .NET Framework Ausnahme geeignet ist, oder wenn die Ausnahme von einer ähnlichen Ausnahme unterschieden werden muss.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. Wenn Sie z. b. ArgumentOutOfRangeException beim Parsen der numerischen Darstellung einer Zeichenfolge, die außerhalb des Bereichs des integralen Ziel Typs liegt, eine Ausnahme auslösen, sollten Sie nicht dieselbe Ausnahme für einen Fehler verwenden, der bewirkt, dass der Aufrufer beim Aufrufen der-Methode nicht die entsprechenden eingeschränkten Werte bereitstellt.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.
Die- Exception Klasse ist die Basisklasse aller Ausnahmen in der .NET Framework.The Exception class is the base class of all exceptions in the .NET Framework. Viele abgeleitete Klassen basieren auf dem geerbten Verhalten der Member der- Exception Klasse. Sie überschreiben nicht die Member von Exception und definieren keine eindeutigen Member.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.
So definieren Sie eine eigene Ausnahme Klasse:To define your own exception class:
Definieren Sie eine Klasse, die von erbt Exception .Define a class that inherits from Exception. Definieren Sie ggf. alle eindeutigen Member, die von der Klasse benötigt werden, um zusätzliche Informationen zur Ausnahme bereitzustellen.If necessary, define any unique members needed by your class to provide additional information about the exception. Beispielsweise enthält die- ArgumentException Klasse eine- ParamName Eigenschaft, die den Namen des Parameters angibt, dessen Argument die Ausnahme verursacht hat, und die- RegexMatchTimeoutException Eigenschaft enthält eine- MatchTimeout Eigenschaft, die das Timeout Intervall angibt.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.
Überschreiben Sie ggf. geerbte Member, deren Funktionalität Sie ändern oder ändern möchten.If necessary, override any inherited members whose functionality you want to change or modify. Beachten Sie, dass die meisten vorhandenen abgeleiteten Klassen von Exception das Verhalten von geerbten Membern nicht überschreiben.Note that most existing derived classes of Exception do not override the behavior of inherited members.
Bestimmen Sie, ob das benutzerdefinierte Exception-Objekt serialisierbar ist.Determine whether your custom exception object is serializable. Mithilfe der Serialisierung können Sie Informationen zu der Ausnahme speichern und zulassen, dass Ausnahme Informationen von einem Server und einem Client Proxy in einem Remotingkontext freigegeben werden.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. Um das Ausnahme Objekt serialisierbar zu machen, markieren Sie es mit dem- SerializableAttribute Attribut.To make the exception object serializable, mark it with the SerializableAttribute attribute.
Definieren Sie die Konstruktoren der Ausnahme Klasse.Define the constructors of your exception class. Normalerweise verfügen Ausnahme Klassen über einen oder mehrere der folgenden Konstruktoren:Typically, exception classes have one or more of the following constructors:
Exception(), der Standardwerte verwendet, um die Eigenschaften eines neuen Ausnahme Objekts zu initialisieren.Exception(), which uses default values to initialize the properties of a new exception object.
Exception(String): Initialisiert ein neues Exception-Objekt mit einer angegebenen Fehlermeldung.Exception(String), which initializes a new exception object with a specified error message.
Exception(String, Exception): Initialisiert ein neues Exception-Objekt mit einer angegebenen Fehlermeldung und einer angegebenen inneren Ausnahme.Exception(String, Exception), which initializes a new exception object with a specified error message and inner exception.
Exception(SerializationInfo, StreamingContext), bei dem es sich um einen Konstruktor handelt, der
protected
ein neues Ausnahme Objekt aus serialisierten Daten initialisiert.Exception(SerializationInfo, StreamingContext), which is aprotected
constructor that initializes a new exception object from serialized data. Sie sollten diesen Konstruktor implementieren, wenn Sie ausgewählt haben, dass das Ausnahme Objekt serialisierbar ist.You should implement this constructor if you've chosen to make your exception object serializable.
Das folgende Beispiel veranschaulicht die Verwendung einer benutzerdefinierten Ausnahme Klasse.The following example illustrates the use of a custom exception class. Es definiert eine- NotPrimeException
Ausnahme, die ausgelöst wird, wenn ein Client versucht, eine Sequenz von Primzahlen abzurufen, indem er eine Startnummer angibt, die nicht Primzahlen ist.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. Die Ausnahme definiert eine neue Eigenschaft, NonPrime
, die die nicht-Primzahl zurückgibt, die die Ausnahme verursacht hat.The exception defines a new property, NonPrime
, that returns the non-prime number that caused the exception. Neben der Implementierung eines geschützten Parameter losen Konstruktors und eines Konstruktors mit SerializationInfo -und- StreamingContext Parametern für die Serialisierung definiert die- NotPrimeException
Klasse drei zusätzliche Konstruktoren, um die-Eigenschaft zu unterstützen 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. Jeder Konstruktor ruft zusätzlich zur Beibehaltung des Werts der nicht-Primzahlen einen Basisklassenkonstruktor auf.Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. Die- NotPrimeException
Klasse wird auch mit dem- SerializableAttribute Attribut gekennzeichnet.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
Die PrimeNumberGenerator
im folgenden Beispiel gezeigte-Klasse verwendet das-Sieb von Eratosthenes, um die Reihenfolge von Primzahlen von 2 bis zu einem vom Client im aufrufskonstruktor angegebenen Grenzwert zu berechnen.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. Die- GetPrimesFrom
Methode gibt alle Primzahlen zurück, die größer oder gleich einer angegebenen unteren Grenze sind, aber löst eine aus, NotPrimeException
Wenn diese untere Grenze keine Primzahl ist.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
Im folgenden Beispiel werden zwei Aufrufe an die GetPrimesFrom
-Methode mit nicht-Primzahlen durchführt, von denen eine die Grenzen der Anwendungsdomäne überschreitet.The following example makes two calls to the GetPrimesFrom
method with non-prime numbers, one of which crosses application domain boundaries. In beiden Fällen wird die Ausnahme ausgelöst und erfolgreich im Client Code behandelt.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-Runtime und .NET Framework 4.5.1Windows Runtime and .NET Framework 4.5.1
In .net für Windows 8. x Store-Apps für Windows 8 gehen einige Ausnahme Informationen in der Regel verloren, wenn eine Ausnahme durch Non-.NET Framework-Stapel Rahmen weitergegeben wird.In .NET for Windows 8.x Store apps for Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. Beginnend mit dem .NET Framework 4.5.1 und Windows 8.1 verwendet der Common Language Runtime weiterhin das ursprüngliche Objekt, Exception das ausgelöst wurde, es sei denn, diese Ausnahme wurde in einem Non-.NET Framework-Stapel Rahmen geändert.Starting with the .NET Framework 4.5.1 and Windows 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.
Konstruktoren
Exception() |
Initialisiert eine neue Instanz der Exception-Klasse.Initializes a new instance of the Exception class. |
Exception(SerializationInfo, StreamingContext) |
Initialisiert eine neue Instanz der Exception-Klasse mit serialisierten Daten.Initializes a new instance of the Exception class with serialized data. |
Exception(String) |
Initialisiert eine neue Instanz der Exception-Klasse mit einer angegebenen Fehlermeldung.Initializes a new instance of the Exception class with a specified error message. |
Exception(String, Exception) |
Initialisiert eine neue Instanz der Exception-Klasse mit einer angegebenen Fehlermeldung und einem Verweis auf die innere Ausnahme, die diese Ausnahme ausgelöst hat.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. |
Eigenschaften
Data |
Ruft eine Auflistung von Schlüssel-Wert-Paaren ab, die zusätzliche benutzerdefinierte Informationen zur Ausnahme bereitstellen.Gets a collection of key/value pairs that provide additional user-defined information about the exception. |
HelpLink |
Ruft einen Link zur Hilfedatei ab, die dieser Ausnahme zugeordnet ist, oder legt einen Link fest.Gets or sets a link to the help file associated with this exception. |
HResult |
Ruft HRESULT ab oder legt HRESULT fest. Dies ist ein codierter Wert, der einer bestimmten Ausnahme zugeordnet ist.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. |
InnerException |
Ruft die Exception-Instanz ab, die die aktuelle Ausnahme verursacht hat.Gets the Exception instance that caused the current exception. |
Message |
Ruft eine Meldung ab, mit der die aktuelle Ausnahme beschrieben wird.Gets a message that describes the current exception. |
Source |
Gibt den Namen der Anwendung oder des Objekts zurück, die bzw. das den Fehler verursacht hat, oder legt diesen fest.Gets or sets the name of the application or the object that causes the error. |
StackTrace |
Ruft eine Zeichenfolgendarstellung der unmittelbaren Frames in der Aufrufliste ab.Gets a string representation of the immediate frames on the call stack. |
TargetSite |
Ruft die Methode ab, die die aktuelle Ausnahme auslöst.Gets the method that throws the current exception. |
Methoden
Equals(Object) |
Bestimmt, ob das angegebene Objekt gleich dem aktuellen Objekt ist.Determines whether the specified object is equal to the current object. (Geerbt von Object) |
GetBaseException() |
Gibt beim Überschreiben in einer abgeleiteten Klasse eine Exception zurück, die die Grundursache für eine oder mehrere nachfolgende Ausnahmen ist.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. |
GetHashCode() |
Fungiert als Standardhashfunktion.Serves as the default hash function. (Geerbt von Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Legt beim Überschreiben in einer abgeleiteten Klasse die SerializationInfo mit Informationen über die Ausnahme fest.When overridden in a derived class, sets the SerializationInfo with information about the exception. |
GetType() |
Ruft den Laufzeittyp der aktuellen Instanz ab.Gets the runtime type of the current instance. |
GetType() |
Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance. (Geerbt von Object) |
MemberwiseClone() |
Erstellt eine flache Kopie des aktuellen Object.Creates a shallow copy of the current Object. (Geerbt von Object) |
ToString() |
Erstellt eine Zeichenfolgendarstellung der aktuellen Ausnahme und gibt diese zurück.Creates and returns a string representation of the current exception. |
Ereignisse
SerializeObjectState |
Tritt auf, wenn eine Ausnahme serialisiert wird, um ein Ausnahmezustandsobjekt mit serialisierten Daten über die Ausnahme zu erstellen.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. |