Exception 建構函式

定義

初始化 Exception 類別的新執行個體。

多載

Exception()

初始化 Exception 類別的新執行個體。

Exception(String)

使用指定的錯誤訊息,初始化 Exception 類別的新執行個體。

Exception(SerializationInfo, StreamingContext)
已淘汰.

使用序列化資料,初始化 Exception 類別的新執行個體。

Exception(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 Exception 類別的新執行個體。

Exception()

Source:
Exception.CoreCLR.cs
Source:
Exception.CoreCLR.cs
Source:
Exception.CoreCLR.cs

初始化 Exception 類別的新執行個體。

public:
 Exception();
public Exception ();
Public Sub New ()

範例

下列程式碼範例會 Exception 衍生使用預先定義訊息的 。 此程式碼示範針對衍生類別和基 Exception 類使用無參數建構函式。

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

namespace NDP_UE_CPP
{

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

   };


   // Half throws a base exception if the input is not even.
   int Half( int input )
   {
      if ( input % 2 != 0 )
            throw gcnew Exception;
      else
            return input / 2;
   }


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


   // CalcHalf calls Half and catches any thrown exceptions.
   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.
   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() );
      }

   }

}

int 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" );
   NDP_UE_CPP::CalcHalf( 12 );
   NDP_UE_CPP::CalcHalf( 15 );
   Console::WriteLine( "\nHere, an exception is thrown using the \n"
   "parameterless constructor of a derived class.\n" );
   NDP_UE_CPP::CalcHalf2( 24 );
   NDP_UE_CPP::CalcHalf2( 27 );
}

/*
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_CPP.Half(Int32 input)
   at NDP_UE_CPP.CalcHalf(Int32 input)

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

Half of 24 is 12.
NDP_UE_CPP.NotEvenException: The argument to a function requiring even input is
 not divisible by 2.
   at NDP_UE_CPP.Half2(Int32 input)
   at NDP_UE_CPP.CalcHalf2(Int32 input)
*/
// 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)
*/
// Example for the Exception() constructor.
open System

// Derive an exception with a predefined message.
type NotEvenException() =
    inherit Exception "The argument to a function requiring even input is not divisible by 2."

// half throws a base exception if the input is not even.
let half input =
    if input % 2 <> 0 then
        raise (Exception())
    else input / 2

// half2 throws a derived exception if the input is not even.
let half2 input =
    if input % 2 <> 0 then
        raise (NotEvenException())
    else input / 2

// calcHalf calls Half and catches any thrown exceptions.
let calcHalf input =
    try
        let halfInput = half input
        printfn $"Half of {input} is {halfInput}."
    with ex ->
        printfn $"{ex}"

// calcHalf2 calls Half2 and catches any thrown exceptions.
let calcHalf2 input =
    try
        let halfInput = half2 input
        printfn $"Half of {input} is {halfInput}."
    with ex ->
        printfn $"{ex}"

printfn "This example of the Exception() constructor generates the following output." 
printfn "\nHere, an exception is thrown using the \nparameterless constructor of the base class.\n"

calcHalf 12
calcHalf 15

printfn "\nHere, an exception is thrown using the \nparameterless constructor of a derived class.\n"

calcHalf2 24
calcHalf2 27 


// 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_FS.half(Int32 input)
//    at at NDP_UE_FS.calcHalf(Int32 input)
//
// Here, an exception is thrown using the
// parameterless constructor of a derived class.
//
// Half of 24 is 12.
// NDP_UE_FS+NotEvenException: The argument to a function requiring even input is
// not divisible by 2.
//    at NDP_UE_FS.half2(Int32 input)
//    at NDP_UE_FS.calcHalf2(Int32 input)
' Example for the Exception( ) constructor.
Namespace NDP_UE_VB

    ' Derive an exception with a predefined message.
    Class NotEvenException
        Inherits Exception
           
        Public Sub New( )
            MyBase.New( _
                "The argument to a function requiring " & _
                "even input is not divisible by 2." )
        End Sub
    End Class

    Module NewExceptionDemo
       
        Sub Main( )
            Console.WriteLine( _
                "This example of the Exception( ) constructor " & _
                "generates the following output." )
            Console.WriteLine( vbCrLf & _
                "Here, an exception is thrown using the " & vbCrLf & _
                "parameterless constructor of the base class." & _
                vbCrLf )

            CalcHalf( 12 )
            CalcHalf( 15 )
              
            Console.WriteLine(vbCrLf & _
                "Here, an exception is thrown using the " & vbCrLf & _
                "parameterless constructor of a derived class." & _
                vbCrLf )

            CalcHalf2( 24 )
            CalcHalf2( 27 )
        End Sub
           
        ' Half throws a base exception if the input is not even.
        Function Half( input As Integer ) As Integer

            If input Mod 2 <> 0 Then
                Throw New Exception( )
            Else
                Return input / 2
            End If
        End Function ' Half
            
        ' Half2 throws a derived exception if the input is not even.
        Function Half2( input As Integer ) As Integer

            If input Mod 2 <> 0 Then
                Throw New NotEvenException( )
            Else
                Return input / 2
            End If
        End Function ' Half2
            
        ' CalcHalf calls Half and catches any thrown exceptions.
        Sub CalcHalf( input As Integer )

            Try
                Dim halfInput As Integer = Half( input )
                Console.WriteLine( _
                    "Half of {0} is {1}.", input, halfInput )

            Catch ex As Exception
                Console.WriteLine( ex.ToString( ) )
            End Try
        End Sub
           
        ' CalcHalf2 calls Half2 and catches any thrown exceptions.
        Sub CalcHalf2( input As Integer )

            Try
                Dim halfInput As Integer = Half2( input )
                Console.WriteLine( _
                    "Half of {0} is {1}.", input, halfInput )

            Catch ex As Exception
                Console.WriteLine( ex.ToString( ) )
            End Try
        End Sub

    End Module ' NewExceptionDemo
End Namespace ' NDP_UE_VB

' 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_VB.NewExceptionDemo.Half(Int32 input)
'    at NDP_UE_VB.NewExceptionDemo.CalcHalf(Int32 input)
' 
' Here, an exception is thrown using the
' parameterless constructor of a derived class.
' 
' Half of 24 is 12.
' NDP_UE_VB.NotEvenException: The argument to a function requiring even input i
' s not divisible by 2.
'    at NDP_UE_VB.NewExceptionDemo.Half2(Int32 input)
'    at NDP_UE_VB.NewExceptionDemo.CalcHalf2(Int32 input)

備註

這個建構函式會將新執行個體的 Message 屬性初始化為系統提供的訊息,該訊息會描述錯誤並考量目前系統的文化特性。

所有衍生類別都應該提供這個無參數建構函式。 下表顯示 Exception 執行個體的初始屬性值。

屬性
InnerException null 參考 (在 Visual Basic 中為 Nothing)。
Message 系統提供的當地語系化描述。

適用於

Exception(String)

Source:
Exception.cs
Source:
Exception.cs
Source:
Exception.cs

使用指定的錯誤訊息,初始化 Exception 類別的新執行個體。

public:
 Exception(System::String ^ message);
public Exception (string message);
public Exception (string? message);
new Exception : string -> Exception
Public Sub New (message As String)

參數

message
String

描述錯誤的訊息。

範例

下列程式碼範例會 Exception 針對特定條件衍生 的 。 程式碼示範如何針對衍生類別和基 Exception 類使用呼叫端指定的訊息做為參數的建構函式。

// Example for the Exception( String* ) constructor.
using namespace System;

namespace NDP_UE_CPP
{

   // Derive an exception with a specifiable message.
   public ref class NotEvenException: public Exception
   {
   private:
      static String^ notEvenMessage = "The argument to a function requiring "
      "even input is not divisible by 2.";

   public:
      NotEvenException()
         : Exception( notEvenMessage )
      {}

      NotEvenException( String^ auxMessage )
         : Exception( String::Format( "{0} - {1}", auxMessage, notEvenMessage ) )
      {}

   };


   // Half throws a base exception if the input is not even.
   int Half( int input )
   {
      if ( input % 2 != 0 )
            throw gcnew 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.
   int Half2( int input )
   {
      if ( input % 2 != 0 )
            throw gcnew NotEvenException( String::Format( "Invalid argument: {0}", input ) );
      else
            return input / 2;
   }


   // CalcHalf calls Half and catches any thrown exceptions.
   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.
   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() );
      }

   }

}

int 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" );
   NDP_UE_CPP::CalcHalf( 18 );
   NDP_UE_CPP::CalcHalf( 21 );
   Console::WriteLine( "\nHere, an exception is thrown using the \n"
   "constructor of a derived class.\n" );
   NDP_UE_CPP::CalcHalf2( 30 );
   NDP_UE_CPP::CalcHalf2( 33 );
}

/*
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_CPP.Half(Int32 input)
   at NDP_UE_CPP.CalcHalf(Int32 input)

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

Half of 30 is 15.
NDP_UE_CPP.NotEvenException: Invalid argument: 33 - The argument to a function
requiring even input is not divisible by 2.
   at NDP_UE_CPP.Half2(Int32 input)
   at NDP_UE_CPP.CalcHalf2(Int32 input)
*/
// 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)
*/
// Example for the Exception(string) constructor.
open System

let notEvenMessage = "The argument to a function requiring even input is not divisible by 2."

// Derive an exception with a specifiable message.
type NotEvenException =
    inherit Exception
    new () = { inherit Exception(notEvenMessage) }
    new (auxMessage) = { inherit Exception($"{auxMessage} - {notEvenMessage}") }

// half throws a base exception if the input is not even.
let half input =
    if input % 2 <> 0 then
        raise (Exception $"The argument {input} is not divisible by 2.")
    else input / 2

// half2 throws a derived exception if the input is not even.
let half2 input =
    if input % 2 <> 0 then
        raise (NotEvenException $"Invalid argument: {input}")
    else input / 2

// calcHalf calls Half and catches any thrown exceptions.
let calcHalf input =
    try
        let halfInput = half input
        printfn $"Half of {input} is {halfInput}."
    with ex ->
        printfn $"{ex}"

// calcHalf2 calls Half2 and catches any thrown exceptions.
let calcHalf2 input =
    try
        let halfInput = half2 input
        printfn $"Half of {input} is {halfInput}."
    with ex ->
        printfn $"{ex}"

printfn "This example of the Exception(string)\nconstructor generates the following output."
printfn "\nHere, an exception is thrown using the \nconstructor of the base class.\n"

calcHalf 18
calcHalf 21

printfn "\nHere, an exception is thrown using the \nconstructor of a derived class.\n"

calcHalf2 30
calcHalf2 33


// 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_FS_2.half(Int32 input)
//    at NDP_UE_FS_2.calcHalf(Int32 input)
//
// Here, an exception is thrown using the
// constructor of a derived class.
//
// Half of 30 is 15.
// NDP_UE_FS_2+NotEvenException: Invalid argument: 33 - The argument to a function r
// equiring even input is not divisible by 2.
//    at NDP_UE_FS_2.half2(Int32 input)
//    at NDP_UE_FS_2.calcHalf2(Int32 input)
' Example for the Exception( String ) constructor( String ).
Namespace NDP_UE_VB

    ' Derive an exception with a specifiable message.
    Class NotEvenException
        Inherits Exception

        Private Const notEvenMessage As String = _
            "The argument to a function requiring " & _
            "even input is not divisible by 2."
           
        Public Sub New()
            MyBase.New(notEvenMessage)
        End Sub
           
        Public Sub New(auxMessage As String)
            MyBase.New(String.Format("{0} - {1}", _
                auxMessage, notEvenMessage))
        End Sub
    End Class

    Module NewSExceptionDemo
       
        Sub Main()
            Console.WriteLine( _
                "This example of the Exception( String )" & vbCrLf & _
                "constructor generates the following output." )
            Console.WriteLine( vbCrLf & _
                "Here, an exception is thrown using the " & vbCrLf & _
                "constructor of the base class." & vbCrLf )

            CalcHalf(18)
            CalcHalf(21)
              
            Console.WriteLine(vbCrLf & _
                "Here, an exception is thrown using the " & vbCrLf & _
                "constructor of a derived class." & vbCrLf )

            CalcHalf2(30)
            CalcHalf2(33)
        End Sub
           
        ' Half throws a base exception if the input is not even.
        Function Half(input As Integer) As Integer

            If input Mod 2 <> 0 Then
                Throw New Exception( String.Format( _
                    "The argument {0} is not divisible by 2.", _
                    input ) )
            Else
                Return input / 2
            End If
        End Function ' Half
            
        ' Half2 throws a derived exception if the input is not even.
        Function Half2(input As Integer) As Integer

            If input Mod 2 <> 0 Then
                Throw New NotEvenException( _
                    String.Format( "Invalid argument: {0}", input ) )
            Else
                Return input / 2
            End If
        End Function ' Half2
            
        ' CalcHalf calls Half and catches any thrown exceptions.
        Sub CalcHalf(input As Integer)

            Try
                Dim halfInput As Integer = Half(input)
                Console.WriteLine( _
                    "Half of {0} is {1}.", input, halfInput )

            Catch ex As Exception
                Console.WriteLine( ex.ToString( ) )
            End Try
        End Sub
           
           
        ' CalcHalf2 calls Half2 and catches any thrown exceptions.
        Sub CalcHalf2( input As Integer )

            Try
                Dim halfInput As Integer = Half2( input )
                Console.WriteLine( _
                    "Half of {0} is {1}.", input, halfInput )

            Catch ex As Exception
                Console.WriteLine( ex.ToString( ) )
            End Try
        End Sub

    End Module ' NewSExceptionDemo
End Namespace ' NDP_UE_VB

' 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_VB.NewSExceptionDemo.Half(Int32 input)
'    at NDP_UE_VB.NewSExceptionDemo.CalcHalf(Int32 input)
' 
' Here, an exception is thrown using the
' constructor of a derived class.
' 
' Half of 30 is 15.
' NDP_UE_VB.NotEvenException: Invalid argument: 33 - The argument to a function
'  requiring even input is not divisible by 2.
'    at NDP_UE_VB.NewSExceptionDemo.Half2(Int32 input)
'    at NDP_UE_VB.NewSExceptionDemo.CalcHalf2(Int32 input)

備註

這個建構函式會使用 message 參數,初始化 Message 新實例的 屬性。 message如果 參數為 null ,則這與呼叫建 Exception 構函式相同。

下表顯示 Exception 執行個體的初始屬性值。

屬性
InnerException null 參考 (在 Visual Basic 中為 Nothing)。
Message 錯誤訊息字串。

適用於

Exception(SerializationInfo, StreamingContext)

Source:
Exception.CoreCLR.cs
Source:
Exception.CoreCLR.cs
Source:
Exception.CoreCLR.cs

警告

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

使用序列化資料,初始化 Exception 類別的新執行個體。

protected:
 Exception(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Exception (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[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);
new Exception : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> Exception
[<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}")>]
new Exception : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> Exception
Protected Sub New (info As SerializationInfo, context As StreamingContext)

參數

info
SerializationInfo

SerializationInfo,包含所擲回之例外狀況的相關序列化物件資料。

context
StreamingContext

包含有關來源或目的端內容資訊的 StreamingContext

屬性

例外狀況

infonull

類別名稱為 nullHResult 為零 (0)。

範例

下列程式碼範例會定義衍生的可 Exception 序列化類別。 程式碼會強制除以 0 錯誤,然後使用 () SerializationInfoStreamingContext 建構函式建立衍生例外狀況的實例。 程式碼會將 實例序列化為檔案、將檔案還原序列化為新的例外狀況,它會擲回該例外狀況,然後攔截並顯示例外狀況的資料。

#using <System.Runtime.Serialization.Formatters.Soap.dll>

using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters::Soap;

// Define a serializable derived exception class.

[Serializable]
ref class SecondLevelException: public Exception, public ISerializable
{
public:

   // This public constructor is used by class instantiators.
   SecondLevelException( String^ message, Exception^ inner )
      : Exception( message, inner )
   {
      HelpLink = "http://MSDN.Microsoft.com";
      Source = "Exception_Class_Samples";
   }


protected:

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


public:

   // GetObjectData performs a custom serialization.
   [System::Security::Permissions::SecurityPermissionAttribute
   (System::Security::Permissions::SecurityAction::LinkDemand, 
   Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)]
   virtual void GetObjectData( SerializationInfo^ info, StreamingContext context ) override
   {
      
      // Change the case of two properties, and then use the 
      // method of the base class.
      HelpLink = HelpLink->ToLower();
      Source = Source->ToUpperInvariant();
      Exception::GetObjectData( info, context );
   }

};

int 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 = gcnew 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 = gcnew FileStream( "NewException.dat",FileMode::Create );
         try
         {
            
            // Serialize the derived exception.
            SoapFormatter^ formatter = gcnew SoapFormatter( nullptr,StreamingContext(StreamingContextStates::File) );
            formatter->Serialize( stream, newExcept );
            
            // Rewind the stream and deserialize the 
            // exception.
            stream->Position = 0;
            SecondLevelException^ deserExcept = dynamic_cast<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 of the Exception constructor and Exception.GetObjectData
with SerializationInfo and StreamingContext parameters generates
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

SecondLevelException: Forced a division by 0 and threw another exception. ---> S
ystem.DivideByZeroException: Attempted to divide by zero.
   at main()
   --- End of inner exception stack trace ---
   at main()

*/
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()
*/
open System
open System.IO
open System.Runtime.Serialization
open System.Runtime.Serialization.Formatters.Soap
open System.Security.Permissions

 // Define a serializable derived exception class.
 [<Serializable>]
 type SecondLevelException =
    inherit Exception

    interface ISerializable with
        // GetObjectData performs a custom serialization.
        member this.GetObjectData(info: SerializationInfo, context: StreamingContext) =
            // Change the case of two properties, and then use the
            // method of the base class.
            this.HelpLink <- this.HelpLink.ToLower()
            this.Source <- this.Source.ToUpperInvariant()

            base.GetObjectData( info, context )
    // This public constructor is used by class instantiators.
    new (message: string, inner: Exception) as this =
        { inherit Exception(message, inner) }
        then
            this.HelpLink <- "http://MSDN.Microsoft.com"
            this.Source <- "Exception_Class_Samples" 

    // This protected constructor is used for deserialization.
    new (info: SerializationInfo, context: StreamingContext) =
        { inherit Exception(info, context) }

printfn 
    """This example of the Exception constructor and Exception.GetObjectData
with SerializationInfo and StreamingContext parameters generates 
the following output.
"""

try
    // This code forces a division by 0 and catches the
    // resulting exception.
    try
        let zero = 0
        let ecks = 1 / zero
        ()
    with ex ->
        // Create a new exception to throw again.
        let newExcept = SecondLevelException("Forced a division by 0 and threw another exception.", ex)

        printfn "Forced a division by 0, caught the resulting exception, \nand created a derived exception:\n"
        printfn $"HelpLink: {newExcept.HelpLink}"
        printfn $"Source:   {newExcept.Source}"

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

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

            // Rewind the stream and deserialize the
            // exception.
            stream.Position <- 0L
            let deserExcept = formatter.Deserialize stream :?> SecondLevelException

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

            // Throw the deserialized exception again.
            raise deserExcept
        with :? SerializationException as se -> 
            printfn $"Failed to serialize: {se}"

with ex ->
    printfn $"HelpLink: {ex.HelpLink}"
    printfn $"Source:   {ex.Source}"
    printfn $"\n{ex}"

// 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_FS_3+SecondLevelException: Forced a division by 0 and threw another except
//     ion. ---> System.DivideByZeroException: Attempted to divide by zero.
//        at <StartupCode$fs>.$NDP_UE_FS_3.main@()
//        --- End of inner exception stack trace ---
//        at <StartupCode$fs>.$NDP_UE_FS_3.main@()
' If compiling with the Visual Basic compiler (vbc.exe) from the command
' prompt, be sure to add the following switch:
'    /reference:System.Runtime.Serialization.Formatters.Soap.dll 
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Security.Permissions

 ' Define a serializable derived exception class.
 <Serializable()>  _
 Class SecondLevelException
     Inherits Exception

     ' This public constructor is used by class instantiators.
     Public Sub New( message As String, inner As Exception )
         MyBase.New( message, inner )

         HelpLink = "http://MSDN.Microsoft.com"
         Source = "Exception_Class_Samples"
     End Sub

     ' This protected constructor is used for deserialization.
     Protected Sub New( info As SerializationInfo, _
         context As StreamingContext )
             MyBase.New( info, context )
     End Sub

     ' GetObjectData performs a custom serialization.
     <SecurityPermissionAttribute(SecurityAction.Demand, _
                                  SerializationFormatter:=True)> _
     Overrides Sub GetObjectData( info As SerializationInfo, _
         context As StreamingContext)

         ' Change the case of two properties, and then use the
         ' method of the base class.
         HelpLink = HelpLink.ToLower()
         Source = Source.ToUpperInvariant()

         MyBase.GetObjectData(info, context)
     End Sub
 End Class

 Module SerializationDemo

     Sub Main()
         Console.WriteLine( _
             "This example of the Exception constructor " & _
             "and Exception.GetObjectData " & vbCrLf & _
             "with SerializationInfo and StreamingContext " & _
             "parameters generates " & vbCrLf & _
             "the following output." & vbCrLf )

         ' This code forces a division by 0 and catches the
         ' resulting exception.
         Try
             Try
                 Dim zero As Integer = 0
                 Dim ecks As Integer = 1 \ zero

             ' Create a new exception to throw again.
             Catch ex As Exception

                 Dim newExcept As New SecondLevelException( _
                     "Forced a division by 0 and threw " & _
                     "another exception.", ex )

                 Console.WriteLine( _
                     "Forced a division by 0, caught the " & _
                     "resulting exception, " & vbCrLf & _
                     "and created a derived exception:" & vbCrLf )
                 Console.WriteLine( "HelpLink: {0}", _
                     newExcept.HelpLink )
                 Console.WriteLine( "Source:   {0}", _
                     newExcept.Source )

                 ' This FileStream is used for the serialization.
                 Dim stream As New FileStream( _
                     "NewException.dat", FileMode.Create )

                 ' Serialize the derived exception.
                 Try
                     Dim formatter As New SoapFormatter( Nothing, _
                         New StreamingContext( _
                             StreamingContextStates.File ) )
                     formatter.Serialize( stream, newExcept )

                     ' Rewind the stream and deserialize the
                     ' exception.
                     stream.Position = 0
                     Dim deserExcept As SecondLevelException = _
                         CType( formatter.Deserialize( stream ), _
                             SecondLevelException )

                     Console.WriteLine( vbCrLf & _
                         "Serialized the exception, and then " & _
                         "deserialized the resulting stream " & _
                         "into a " & vbCrLf & "new exception. " & _
                         "The deserialization changed the case " & _
                         "of certain properties:" & vbCrLf )

                     ' Throw the deserialized exception again.
                     Throw deserExcept

                 Catch se As SerializationException
                     Console.WriteLine( "Failed to serialize: {0}", _
                         se.ToString( ) )

                 Finally
                     stream.Close( )
                 End Try
             End Try
         Catch ex As Exception
             Console.WriteLine( "HelpLink: {0}", ex.HelpLink )
             Console.WriteLine( "Source:   {0}", ex.Source )

             Console.WriteLine( )
             Console.WriteLine( ex.ToString( ) )
         End Try
     End Sub
 End Module
' 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_VB.SecondLevelException: Forced a division by 0 and threw another exce
' ption. ---> System.DivideByZeroException: Attempted to divide by zero.
'    at NDP_UE_VB.SerializationDemo.Main()
'    --- End of inner exception stack trace ---
'    at NDP_UE_VB.SerializationDemo.Main()

備註

這個建構函式是在還原序列化期間呼叫,以便重新組成透過資料流傳輸的例外狀況物件。 如需詳細資訊,請參閱 < XML 和 SOAP 序列化

另請參閱

適用於

Exception(String, Exception)

Source:
Exception.cs
Source:
Exception.cs
Source:
Exception.cs

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 Exception 類別的新執行個體。

public:
 Exception(System::String ^ message, Exception ^ innerException);
public Exception (string message, Exception innerException);
public Exception (string? message, Exception? innerException);
new Exception : string * Exception -> Exception
Public Sub New (message As String, innerException As Exception)

參數

message
String

解釋例外狀況原因的錯誤訊息。

innerException
Exception

造成目前例外狀況的例外狀況,若未指定內部例外狀況,則為 null 參考 (Visual Basic 中為 Nothing)。

範例

下列程式碼範例會 Exception 針對特定條件衍生 的 。 此程式碼示範如何針對衍生類別和基 Exception 類,使用接受訊息和內部例外狀況做為參數的建構函式。

// Example for the Exception( String*, Exception* ) constructor.
using namespace System;

namespace NDP_UE_CPP
{

   // Derive an exception with a specifiable message and inner exception.
   public ref class LogTableOverflowException: public Exception
   {
   private:
      static String^ overflowMessage =  "The log table has overflowed.";

   public:
      LogTableOverflowException()
         : Exception( overflowMessage )
      {}

      LogTableOverflowException( String^ auxMessage )
         : Exception( String::Format( "{0} - {1}", overflowMessage, auxMessage ) )
      {}

      LogTableOverflowException( String^ auxMessage, Exception^ inner )
         : Exception( String::Format( "{0} - {1}", overflowMessage, auxMessage ), inner )
      {}

   };

   public ref class LogTable
   {
   public:
      LogTable( int numElements )
      {
         logArea = gcnew array<String^>(numElements);
         elemInUse = 0;
      }


   protected:
      array<String^>^logArea;
      int elemInUse;

   public:

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

      }

   };


   // Create a log table and force an overflow.
   void ForceOverflow()
   {
      LogTable^ log = gcnew LogTable( 4 );
      try
      {
         for ( int count = 1; ; count++ )
         {
            log->AddRecord( String::Format( "Log record number {0}", count ) );

         }
      }
      catch ( Exception^ ex ) 
      {
         Console::WriteLine( ex->ToString() );
      }

   }

}

int main()
{
   Console::WriteLine( "This example of the Exception( String*, Exception* )\n"
   "constructor generates the following output." );
   Console::WriteLine( "\nExample of a derived exception "
   "that references an inner exception:\n" );
   NDP_UE_CPP::ForceOverflow();
}

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

Example of a derived exception that references an inner exception:

NDP_UE_CPP.LogTableOverflowException: The log table has overflowed. - Record "L
og record number 5" was not logged. ---> System.IndexOutOfRangeException: Index
 was outside the bounds of the array.
   at NDP_UE_CPP.LogTable.AddRecord(String newRecord)
   --- End of inner exception stack trace ---
   at NDP_UE_CPP.LogTable.AddRecord(String newRecord)
   at NDP_UE_CPP.ForceOverflow()
*/
// 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()
*/
// Example for the Exception(string, Exception) constructor.
open System

let overflowMessage = "The log table has overflowed."

// Derive an exception with a specifiable message and inner exception.
type LogTableOverflowException =
    inherit Exception

    new () =  { inherit Exception(overflowMessage) }

    new (auxMessage: string) = 
        { inherit Exception($"{overflowMessage} - {auxMessage}") }

    new (auxMessage: string, inner: Exception) =
        { inherit Exception($"{overflowMessage} - {auxMessage}", inner ) }

type LogTable(numElements: int) =
    let mutable logArea = Array.zeroCreate<string> numElements
    let mutable elemInUse = 0

    // The AddRecord method throws a derived exception
    // if the array bounds exception is caught.
    member _.AddRecord(newRecord: string): int =
        try
            logArea[elemInUse] <- newRecord
            elemInUse <- elemInUse + 1
            elemInUse - 1
        with ex ->
            raise (LogTableOverflowException($"Record \"{newRecord}\" was not logged.", ex ) )

// Create a log table and force an overflow.
let log = LogTable 4

printfn "This example of the Exception(string, Exception)\nconstructor generates the following output."
printfn "\nExample of a derived exception that references an inner exception:\n"
try
    for count = 1 to 1000 do
        log.AddRecord $"Log record number {count}"
        |> ignore
with ex ->
    printfn $"{ex}"


// This example of the Exception(string, Exception)
// constructor generates the following output.
//
// Example of a derived exception that references an inner exception:
//
// NDP_UE_FS_4+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_FS_4.LogTable.AddRecord(String newRecord)
//    --- End of inner exception stack trace ---
//    at NDP_UE_FS_4.LogTable.AddRecord(String newRecord)
//    at <StartupCode$fs>.$NDP_UE_FS_4.main@()
' Sample for Exception( String, Exception ) constructor.
Namespace NDP_UE_VB

    ' Derive an exception with a specifiable message and inner exception.
    Class LogTableOverflowException
        Inherits Exception

        Private Const overflowMessage As String = _
            "The log table has overflowed."
           
        Public Sub New( )
            MyBase.New( overflowMessage )
        End Sub
           
        Public Sub New( auxMessage As String )
            MyBase.New( String.Format( "{0} - {1}", _
                overflowMessage, auxMessage ) )
        End Sub
           
        Public Sub New( auxMessage As String, inner As Exception )
            MyBase.New( String.Format( "{0} - {1}", _
                overflowMessage, auxMessage ), inner )
        End Sub
    End Class

    Class LogTable
       
        Public Sub New( numElements As Integer )
            logArea = New String( numElements ) { }
            elemInUse = 0
        End Sub
           
        Protected logArea( ) As String
        Protected elemInUse As Integer
           
        ' The AddRecord method throws a derived exception 
        ' if the array bounds exception is caught.
        Public Function AddRecord( newRecord As String ) As Integer

            Try
                Dim curElement as Integer = elemInUse
                logArea( elemInUse ) = newRecord
                elemInUse += 1
                Return curElement

            Catch ex As Exception
                Throw New LogTableOverflowException( String.Format( _
                    "Record ""{0}"" was not logged.", newRecord ), ex )
            End Try
        End Function ' AddRecord
        End Class

        Module OverflowDemo
           
        ' Create a log table and force an overflow.
        Sub Main()
            Dim log As New LogTable(4)
              
            Console.WriteLine( _
                "This example of the Exception( String, Exception )" & _
                vbCrLf & "constructor generates the following output." )
            Console.WriteLine( vbCrLf & _
                "Example of a derived exception " & vbCrLf & _
                "that references an inner exception:" & vbCrLf )
            Try
                Dim count As Integer = 0
                 
                Do
                    log.AddRecord( _
                        String.Format( _
                            "Log record number {0}", count ) )
                    count += 1
                Loop

            Catch ex As Exception
                Console.WriteLine( ex.ToString( ) )
            End Try
        End Sub

    End Module ' OverflowDemo
End Namespace ' NDP_UE_VB

' This example of the Exception( String, Exception )
' constructor generates the following output.
' 
' Example of a derived exception
' that references an inner exception:
' 
' NDP_UE_VB.LogTableOverflowException: The log table has overflowed. - Record "
' Log record number 5" was not logged. ---> System.IndexOutOfRangeException: In
' dex was outside the bounds of the array.
'    at NDP_UE_VB.LogTable.AddRecord(String newRecord)
'    --- End of inner exception stack trace ---
'    at NDP_UE_VB.LogTable.AddRecord(String newRecord)
'    at NDP_UE_VB.OverflowDemo.Main()

備註

被擲回以做為前一個例外狀況直接結果的例外狀況,應該在 InnerException 屬性中包含對前一個例外狀況的參考。 InnerException 屬性會傳回與傳入建構函式中相同的值;如果 Nothing 屬性不提供內部例外值給建構函式,則傳回 null 參考 (在 Visual Basic 中為 InnerException)。

下表顯示 Exception 執行個體的初始屬性值。

屬性
InnerException 內部例外狀況參考。
Message 錯誤訊息字串。

適用於