Auf Englisch lesen

Freigeben über


Exception Konstruktoren

Definition

Initialisiert eine neue Instanz der Exception-Klasse.

Überlädt

Exception()

Initialisiert eine neue Instanz der Exception-Klasse.

Exception(String)

Initialisiert eine neue Instanz der Exception-Klasse mit einer angegebenen Fehlermeldung.

Exception(SerializationInfo, StreamingContext)
Veraltet.

Initialisiert eine neue Instanz der Exception-Klasse mit serialisierten Daten.

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.

Exception()

Quelle:
Exception.CoreCLR.cs
Quelle:
Exception.CoreCLR.cs
Quelle:
Exception.CoreCLR.cs

Initialisiert eine neue Instanz der Exception-Klasse.

C#
public Exception ();

Beispiele

Im folgenden Codebeispiel wird eine Exception abgeleitet, die eine vordefinierte Nachricht verwendet. Der Code veranschaulicht die Verwendung des parameterlosen Konstruktors für die abgeleitete Klasse und die Basisklasse Exception .

C#
// Example for the Exception( ) constructor.
using System;

namespace NDP_UE_CS
{
    // Derive an exception with a predefined message.
    class NotEvenException : Exception
    {
        public NotEvenException( ) :
            base( "The argument to a function requiring " +
                "even input is not divisible by 2." )
        { }
    }

    class NewExceptionDemo
    {
        public static void Main()
        {
            Console.WriteLine(
                "This example of the Exception( ) constructor " +
                "generates the following output." );
            Console.WriteLine(
                "\nHere, an exception is thrown using the \n" +
                "parameterless constructor of the base class.\n" );

            CalcHalf( 12 );
            CalcHalf( 15 );

            Console.WriteLine(
                "\nHere, an exception is thrown using the \n" +
                "parameterless constructor of a derived class.\n" );

            CalcHalf2( 24 );
            CalcHalf2( 27 );
        }
        
        // Half throws a base exception if the input is not even.
        static int Half( int input )
        {
            if( input % 2 != 0 )
                throw new Exception( );

            else return input / 2;
        }

        // Half2 throws a derived exception if the input is not even.
        static int Half2( int input )
        {
            if( input % 2 != 0 )
                throw new NotEvenException( );

            else return input / 2;
        }

        // CalcHalf calls Half and catches any thrown exceptions.
        static void CalcHalf(int input )
        {
            try
            {
                int halfInput = Half( input );
                Console.WriteLine(
                    "Half of {0} is {1}.", input, halfInput );
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }

        // CalcHalf2 calls Half2 and catches any thrown exceptions.
        static void CalcHalf2(int input )
        {
            try
            {
                int halfInput = Half2( input );
                Console.WriteLine(
                    "Half of {0} is {1}.", input, halfInput );
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }
    }
}

/*
This example of the Exception( ) constructor generates the following output.

Here, an exception is thrown using the
parameterless constructor of the base class.

Half of 12 is 6.
System.Exception: Exception of type System.Exception was thrown.
   at NDP_UE_CS.NewExceptionDemo.Half(Int32 input)
   at NDP_UE_CS.NewExceptionDemo.CalcHalf(Int32 input)

Here, an exception is thrown using the
parameterless constructor of a derived class.

Half of 24 is 12.
NDP_UE_CS.NotEvenException: The argument to a function requiring even input is
not divisible by 2.
   at NDP_UE_CS.NewExceptionDemo.Half2(Int32 input)
   at NDP_UE_CS.NewExceptionDemo.CalcHalf2(Int32 input)
*/

Hinweise

Dieser Konstruktor initialisiert die Message-Eigenschaft der neuen Instanz mit einer Systemmeldung, die den Fehler beschreibt und die aktuelle Systemkultur berücksichtigt.

Alle abgeleiteten Klassen sollten diesen parameterlosen Konstruktor bereitstellen. In der folgenden Tabelle werden die anfänglichen Eigenschaftenwerte für eine Exception-Instanz aufgeführt.

Eigenschaft Wert
InnerException Ein NULL-Verweis (Nothing in Visual Basic).
Message Eine im System enthaltene lokalisierte Beschreibung.

Gilt für:

.NET 9 und andere Versionen
Produkt Versionen
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Exception(String)

Quelle:
Exception.cs
Quelle:
Exception.cs
Quelle:
Exception.cs

Initialisiert eine neue Instanz der Exception-Klasse mit einer angegebenen Fehlermeldung.

C#
public Exception (string message);
C#
public Exception (string? message);

Parameter

message
String

Die Meldung, in der der Fehler beschrieben wird.

Beispiele

Im folgenden Codebeispiel wird eine Exception für eine bestimmte Bedingung abgeleitet. Der Code veranschaulicht die Verwendung des Konstruktors, der eine vom Aufrufer angegebene Nachricht als Parameter sowohl für die abgeleitete Klasse als auch für die Basisklasse Exception verwendet.

C#
// Example for the Exception( string ) constructor.
using System;

namespace NDP_UE_CS2
{
    // Derive an exception with a specifiable message.
    class NotEvenException : Exception
    {
        const string notEvenMessage =
            "The argument to a function requiring " +
            "even input is not divisible by 2.";

        public NotEvenException( ) :
            base( notEvenMessage )
        { }

        public NotEvenException( string auxMessage ) :
            base( String.Format( "{0} - {1}",
                auxMessage, notEvenMessage ) )
        { }
    }

    class NewSExceptionDemo
    {
        public static void Main()
        {
            Console.WriteLine(
                "This example of the Exception( string )\n" +
                "constructor generates the following output." );
            Console.WriteLine(
                "\nHere, an exception is thrown using the \n" +
                "constructor of the base class.\n" );

            CalcHalf( 18 );
            CalcHalf( 21 );

            Console.WriteLine(
                "\nHere, an exception is thrown using the \n" +
                "constructor of a derived class.\n" );

            CalcHalf2( 30 );
            CalcHalf2( 33 );
        }
        
        // Half throws a base exception if the input is not even.
        static int Half( int input )
        {
            if( input % 2 != 0 )
                throw new Exception( String.Format(
                    "The argument {0} is not divisible by 2.",
                    input ) );

            else return input / 2;
        }

        // Half2 throws a derived exception if the input is not even.
        static int Half2( int input )
        {
            if( input % 2 != 0 )
                throw new NotEvenException(
                    String.Format( "Invalid argument: {0}", input ) );

            else return input / 2;
        }

        // CalcHalf calls Half and catches any thrown exceptions.
        static void CalcHalf(int input )
        {
            try
            {
                int halfInput = Half( input );
                Console.WriteLine(
                    "Half of {0} is {1}.", input, halfInput );
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }

        // CalcHalf2 calls Half2 and catches any thrown exceptions.
        static void CalcHalf2(int input )
        {
            try
            {
                int halfInput = Half2( input );
                Console.WriteLine(
                    "Half of {0} is {1}.", input, halfInput );
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }
    }
}

/*
This example of the Exception( string )
constructor generates the following output.

Here, an exception is thrown using the
constructor of the base class.

Half of 18 is 9.
System.Exception: The argument 21 is not divisible by 2.
   at NDP_UE_CS.NewSExceptionDemo.Half(Int32 input)
   at NDP_UE_CS.NewSExceptionDemo.CalcHalf(Int32 input)

Here, an exception is thrown using the
constructor of a derived class.

Half of 30 is 15.
NDP_UE_CS.NotEvenException: Invalid argument: 33 - The argument to a function r
equiring even input is not divisible by 2.
   at NDP_UE_CS.NewSExceptionDemo.Half2(Int32 input)
   at NDP_UE_CS.NewSExceptionDemo.CalcHalf2(Int32 input)
*/

Hinweise

Dieser Konstruktor initialisiert die Message -Eigenschaft des neuen instance mithilfe des message -Parameters. Wenn der message Parameter ist null, entspricht dies dem Aufrufen des Exception Konstruktors.

In der folgenden Tabelle werden die anfänglichen Eigenschaftenwerte für eine Exception-Instanz aufgeführt.

Eigenschaft Wert
InnerException Ein NULL-Verweis (Nothing in Visual Basic).
Message Die Zeichenfolge der Fehlermeldung.

Gilt für:

.NET 9 und andere Versionen
Produkt Versionen
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Exception(SerializationInfo, StreamingContext)

Quelle:
Exception.CoreCLR.cs
Quelle:
Exception.CoreCLR.cs
Quelle:
Exception.CoreCLR.cs

Achtung

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

Initialisiert eine neue Instanz der Exception-Klasse mit serialisierten Daten.

C#
protected Exception (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
C#
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected Exception (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);

Parameter

info
SerializationInfo

Die SerializationInfo, die die serialisierten Objektdaten für die ausgelöste Ausnahme enthält.

context
StreamingContext

Der StreamingContext, der die Kontextinformationen über die Quelle oder das Ziel enthält.

Attribute

Ausnahmen

info ist null.

Der Klassenname ist null, oder HResult ist 0 (null).

Beispiele

Im folgenden Codebeispiel wird eine abgeleitete serialisierbare Exception Klasse definiert. Der Code erzwingt einen Divide-by-0-Fehler und erstellt dann mithilfe des Konstruktors (SerializationInfo, StreamingContext) eine instance der abgeleiteten Ausnahme. Der Code serialisiert die instance in eine Datei, deserialisiert die Datei in eine neue Ausnahme, die ausgelöst wird, und fängt dann die Daten der Ausnahme ab und zeigt sie an.

C#
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

// Define a serializable derived exception class.
[Serializable]
class SecondLevelException : Exception, ISerializable
{
    // This public constructor is used by class instantiators.
    public SecondLevelException(string message, Exception inner) :
        base(message, inner)
    {
        HelpLink = "http://MSDN.Microsoft.com";
        Source = "Exception_Class_Samples";
    }

    // This protected constructor is used for deserialization.
    protected SecondLevelException(SerializationInfo info,
        StreamingContext context) :
            base(info, context)
    { }

    // GetObjectData performs a custom serialization.
    public override void GetObjectData(SerializationInfo info,
        StreamingContext context)
    {
        // Change the case of two properties, and then use the
        // method of the base class.
        HelpLink = HelpLink.ToLower();
        Source = Source.ToUpperInvariant();

        base.GetObjectData(info, context);
    }
}

class SerializationDemo
{
    public static void Main()
    {
        Console.WriteLine(
            "This example of the Exception constructor " +
            "and Exception.GetObjectData\nwith Serialization" +
            "Info and StreamingContext parameters " +
            "generates \nthe following output.\n");

        try
        {
            // This code forces a division by 0 and catches the
            // resulting exception.
            try
            {
                int zero = 0;
                int ecks = 1 / zero;
            }
            catch (Exception ex)
            {
                // Create a new exception to throw again.
                SecondLevelException newExcept =
                    new SecondLevelException(
                        "Forced a division by 0 and threw " +
                        "another exception.", ex);

                Console.WriteLine(
                    "Forced a division by 0, caught the " +
                    "resulting exception, \n" +
                    "and created a derived exception:\n");
                Console.WriteLine("HelpLink: {0}",
                    newExcept.HelpLink);
                Console.WriteLine("Source:   {0}",
                    newExcept.Source);

                // This FileStream is used for the serialization.
                FileStream stream =
                    new FileStream("NewException.dat",
                        FileMode.Create);

                try
                {
                    // Serialize the derived exception.
                    SoapFormatter formatter =
                        new SoapFormatter(null,
                            new StreamingContext(
                                StreamingContextStates.File));
                    formatter.Serialize(stream, newExcept);

                    // Rewind the stream and deserialize the
                    // exception.
                    stream.Position = 0;
                    SecondLevelException deserExcept =
                        (SecondLevelException)
                            formatter.Deserialize(stream);

                    Console.WriteLine(
                        "\nSerialized the exception, and then " +
                        "deserialized the resulting stream " +
                        "into a \nnew exception. " +
                        "The deserialization changed the case " +
                        "of certain properties:\n");

                    // Throw the deserialized exception again.
                    throw deserExcept;
                }
                catch (SerializationException se)
                {
                    Console.WriteLine("Failed to serialize: {0}",
                        se.ToString());
                }
                finally
                {
                    stream.Close();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("HelpLink: {0}", ex.HelpLink);
            Console.WriteLine("Source:   {0}", ex.Source);

            Console.WriteLine();
            Console.WriteLine(ex.ToString());
        }
    }
}
/*
This example displays the following output.

Forced a division by 0, caught the resulting exception,
and created a derived exception:

HelpLink: http://MSDN.Microsoft.com
Source:   Exception_Class_Samples

Serialized the exception, and then deserialized the resulting stream into a
new exception. The deserialization changed the case of certain properties:

HelpLink: http://msdn.microsoft.com
Source:   EXCEPTION_CLASS_SAMPLES

NDP_UE_CS.SecondLevelException: Forced a division by 0 and threw another except
ion. ---> System.DivideByZeroException: Attempted to divide by zero.
   at NDP_UE_CS.SerializationDemo.Main()
   --- End of inner exception stack trace ---
   at NDP_UE_CS.SerializationDemo.Main()
*/

Hinweise

Dieser Konstruktor wird während der Deserialisierung aufgerufen, um das über einen Datenstrom übertragene Ausnahmeobjekt wieder zusammenzusetzen. Weitere Informationen finden Sie unter XML- und SOAP-Serialisierung.

Weitere Informationen

Gilt für:

.NET 9 und andere Versionen
Produkt Versionen (Veraltet)
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7 (8, 9)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Exception(String, Exception)

Quelle:
Exception.cs
Quelle:
Exception.cs
Quelle:
Exception.cs

Initialisiert eine neue Instanz der Exception-Klasse mit einer angegebenen Fehlermeldung und einem Verweis auf die innere Ausnahme, die diese Ausnahme ausgelöst hat.

C#
public Exception (string message, Exception innerException);
C#
public Exception (string? message, Exception? innerException);

Parameter

message
String

Die Fehlermeldung, in der die Ursache der Ausnahme erklärt wird.

innerException
Exception

Die Ausnahme, die die aktuelle Ausnahme verursacht hat, oder ein Nullverweis (Nothing in Visual Basic), wenn keine innere Ausnahme angegeben ist.

Beispiele

Im folgenden Codebeispiel wird eine Exception für eine bestimmte Bedingung abgeleitet. Der Code veranschaulicht die Verwendung des Konstruktors, der eine Nachricht und eine innere Ausnahme als Parameter akzeptiert, sowohl für die abgeleitete Klasse als auch für die Basisklasse Exception .

C#
// Example for the Exception( string, Exception ) constructor.
using System;

namespace NDP_UE_CS
{
    // Derive an exception with a specifiable message and inner exception.
    class LogTableOverflowException : Exception
    {
        const string overflowMessage =
            "The log table has overflowed.";

        public LogTableOverflowException( ) :
            base( overflowMessage )
        { }

        public LogTableOverflowException( string auxMessage ) :
            base( String.Format( "{0} - {1}",
                overflowMessage, auxMessage ) )
        { }

        public LogTableOverflowException(
            string auxMessage, Exception inner ) :
                base( String.Format( "{0} - {1}",
                    overflowMessage, auxMessage ), inner )
        { }
    }

    class LogTable
    {
        public LogTable( int numElements )
        {
            logArea = new string[ numElements ];
            elemInUse = 0;
        }

        protected string[ ] logArea;
        protected int       elemInUse;

        // The AddRecord method throws a derived exception
        // if the array bounds exception is caught.
        public    int       AddRecord( string newRecord )
        {
            try
            {
                logArea[ elemInUse ] = newRecord;
                return elemInUse++;
            }
            catch( Exception ex )
            {
                throw new LogTableOverflowException(
                    String.Format( "Record \"{0}\" was not logged.",
                        newRecord ), ex );
            }
        }
    }

    class OverflowDemo
    {
        // Create a log table and force an overflow.
        public static void Main()
        {
            LogTable log = new LogTable( 4 );

            Console.WriteLine(
                "This example of the Exception( string, Exception )" +
                "\nconstructor generates the following output." );
            Console.WriteLine(
                "\nExample of a derived exception " +
                "that references an inner exception:\n" );
            try
            {
                for( int count = 1; ; count++ )
                {
                    log.AddRecord(
                        String.Format(
                            "Log record number {0}", count ) );
                }
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }
    }
}

/*
This example of the Exception( string, Exception )
constructor generates the following output.

Example of a derived exception that references an inner exception:

NDP_UE_CS.LogTableOverflowException: The log table has overflowed. - Record "Lo
g record number 5" was not logged. ---> System.IndexOutOfRangeException: Index
was outside the bounds of the array.
   at NDP_UE_CS.LogTable.AddRecord(String newRecord)
   --- End of inner exception stack trace ---
   at NDP_UE_CS.LogTable.AddRecord(String newRecord)
   at NDP_UE_CS.OverflowDemo.Main()
*/

Hinweise

Eine Ausnahme, die als direktes Ergebnis einer vorhergehenden Ausnahme ausgelöst wird, muss in der InnerException-Eigenschaft über einen Verweis auf die vorhergehende Ausnahme verfügen. Die InnerException-Eigenschaft gibt denselben Wert zurück, der an den Konstruktor übergeben wurde, bzw. einen NULL-Verweis (Nothing in Visual Basic), wenn die InnerException-Eigenschaft nicht den Wert für die innere Ausnahme für den Konstruktor bereitstellt.

In der folgenden Tabelle werden die anfänglichen Eigenschaftenwerte für eine Exception-Instanz aufgeführt.

Eigenschaft Wert
InnerException Der Verweis auf die interne Ausnahme.
Message Die Zeichenfolge der Fehlermeldung.

Gilt für:

.NET 9 und andere Versionen
Produkt Versionen
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0