Exceptionとは? わかりやすく解説

Exception クラス

アプリケーションの実行中に発生するエラー表します

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<SerializableAttribute> _
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
Public Class Exception
    Implements ISerializable, _Exception
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType.None)] 
public class Exception : ISerializable, _Exception
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType::None)] 
public ref class Exception : ISerializable,
 _Exception
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */ 
public class Exception implements ISerializable,
 _Exception
SerializableAttribute 
ComVisibleAttribute(true) 
ClassInterfaceAttribute(ClassInterfaceType.None) 
public class Exception implements ISerializable,
 _Exception
解説解説

このクラスは、すべての例外基本クラスです。エラー発生すると、システムまたは現在実行中のアプリケーションは、そのエラーに関する情報格納され例外スローすることによりエラーレポートしますスローされた例外は、アプリケーションまたは既定例外ハンドラによって処理されます。

共通言語ランタイムは、オブジェクトとして例外表現に基づく例外処理モデル提供しまた、プログラム コード例外処理コードそれぞれ try ブロックcatch ブロック分離します。catch ブロック1 つ以上あり、それぞれのブロックは、特定の型の例外処理するように設計されていることも、一方ブロック他方ブロックよりも具体的な例外を受け取るように設計されていることもあります

アプリケーションが、あるブロックアプリケーション コード実行中に発生する例外処理する場合は、そのコードtry ステートメント内部入れる必要がありますtry ステートメント内のアプリケーション コードは、try ブロックです。try ブロックによりスローされた例外処理するアプリケーション コードcatch ステートメント内部入れられcatch ブロック呼ばれます。0 個以上の catch ブロックtry ブロック関連付けられ、それぞれの catch ブロックには、そのブロック処理する例外種類判断するフィルタ含まれています。

try ブロック例外発生すると、その例外処理する catch ブロックが見つかるまで、関連付けられている catch ブロックが、アプリケーション コード内での出現順に検索されます。catch ブロックの型フィルタT または T派生元の型を指定している場合、その catch ブロックT 型の例外処理します例外処理する最初catch ブロックが見つかると、システム検索中断します。そのため、アプリケーション コードでは、このセクション以降の例で示されるように、ある種類を処理する catch ブロックは、その基本となる種類処理する catch ブロックよりも前に指定される必要がありますSystem.Exception処理する catch ブロック最後に指定されます。

現在の try ブロック関連付けられた catch ブロックでは例外処理するブロックが見つからず現在の呼び出しにおいて現在の try ブロックが他の try ブロック入れ子になっている場合は、その外側try ブロック関連付けられた catch ブロック検索されます。例外処理する catch ブロックが見つからない場合は、現在の呼び出しにおける入れ子レベル外側さかのぼって検索が行われます現在の呼び出しの中で例外処理する catch ブロックが見つからない場合、その例外コール スタック渡され上位レベルスタック フレームで、その例外処理する catch ブロック検索されます。コール スタック検索は、その例外処理されるか、そのコール スタックフレームがなくなるまで続けられます。例外処理する catch ブロックが見つからずコール スタック最上位レベル達した場合は、既定例外ハンドラがその例外処理しアプリケーション終了します

例外種類は、次の機能サポートしてます。

Exception 基本クラスには例外2 つカテゴリあります

Exception には、例外コード位置種類ヘルプ ファイル、および理由識別するのに役立つ多くプロパティ含まれています。それらのプロパティには、StackTrace、InnerException、Message、HelpLink、HResult、Source、TargetSite、および Dataあります

2 つ上の例外の間に因果関係があると、InnerException プロパティにはこの情報保持されます。外部例外は、この内例外応答してスローさます。外部例外処理するコードは、先に発生した内部例外からの情報使用して、より的確にエラーを処理できます例外に関する補足情報は、Data プロパティ格納できます

例外オブジェクトの作成中にコンストラクタ渡されエラー メッセージ文字列ローカライズされているため、ResourceManager を使用してリソース ファイルから指定できますローカライズされたリソース詳細については、System.Resources 名前空間概要トピックおよび「リソースパッケージ化配置」を参照してください

例外発生理由に関する詳細情報ユーザー提供するために、HelpLink プロパティヘルプ ファイルURL (または URN) を保持させることができます

Exception は、値 0x80131500 を保持する HRESULT COR_E_EXCEPTION を使用します

Exceptionインスタンス初期プロパティ値の一覧については、Exception コンストラクタトピック参照してください

パフォーマンスに関する注意事項

例外スローしたり処理したりするときには大量システム リソースおよび実行時間使われます。予測可能なイベントフロー制御の処理のためではなく真に異常な状態の場合のみ例外スローしてください。たとえば、アプリケーションでは有効なパラメータメソッド呼び出されることを前提としているので、メソッド引数無効な場合適切な理由例外スローできますメソッド引数無効であるということは、何か異常が発生していることを示してます。これに対してユーザー入力無効である場合例外スローしないでくださいユーザー無効なデータ入力する場合があることは予測可能な事態だからです。このような場合は、ユーザー有効な入力実行する機会与え再試行メカニズム提供します

異常な状況に対して例外スローする場合は、特定の例外適用されるハンドラではなくアプリケーション大半適用される汎用目的例外ハンドラ例外キャッチします。この手法は、エラー大半発生位置周辺検証エラー処理コード使って対応できるものであり、例外スローまたはキャッチ不要であるという考え方基づいてます。汎用目的例外ハンドラキャッチする対象は、アプリケーション任意の場所でスローされ、適切に予測できない例外です。

また、リターン コードが十分である場合例外スローしたり、リターン コード例外変換したりしないください例外キャッチした場合に、それを無視して処理を続行することは避けてください

使用例使用例

ArithmeticException エラー処理するように定義されている catch ブロックを示すコード例は、次のとおりです。DivideByZeroExceptionArithmeticException から派生しDivideByZeroException エラーに対して明示的に定義されcatch ブロックがないため、この catch ブロックは DivideByZeroException エラー受け取ります

Imports System

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 'Main
End Class 'ExceptionTestClass
using System;

class ExceptionTestClass 
{
public static void Main()
 
{
   int x = 0;
      try 
      {
         int y = 100/x;
      }
         catch (ArithmeticException e) 
         {
         Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());
         }
            catch (Exception e) 
            {
            Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
            }
      }    
}
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 );
   }

}

import System.*;

class ExceptionTestClass
{
    public static void main(String[]
 args)
    {
        int x = 0;
        try {
            int y = 100 / x;
        }
        catch (ArithmeticException e) {
            Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());
        }
        catch (System.Exception e) {
            Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
        }
    } //main
} //ExceptionTestClass

C# コード次の出力生成します

ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by
 zero. at ExceptionTestClass.Main()

Visual Basic コード次の出力生成します

ArithmeticException Handler: System.OverflowException: Exception of type System.OverflowException
 was thrown. at ExceptionTestClass.Main()
継承階層継承階層
System.Object
  System.Exception
     派生クラス
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Exception コンストラクタ ()

Exception クラス新しインスタンス初期化します。

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

解説解説
使用例使用例

定義済みメッセージ使用する Exception派生させるコード例次に示します。この例では、基本 Exception クラス派生クラスパラメータ受け取らないコンストラクタ使用方法示します

' Example for the Exception( ) constructor.
Imports System
Imports Microsoft.VisualBasic

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 ' New
    End Class ' NotEvenException

    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 ' Main
           
        ' 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 ' CalcHalf
           
        ' 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 ' CalcHalf2

    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)
// 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.
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.
package NDP_UE_JSL ; 

import System.* ;

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

class NewExceptionDemo
{
    public static void main(String[]
 args)
    {
        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);
    } //main

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

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

    // 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}.", 
                System.Convert.ToString(input), 
                System.Convert.ToString(halfInput));
        }
        catch (System.Exception ex) {
            Console.WriteLine(ex.toString());
        }
    } //CalcHalf

    // 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}.", 
                System.Convert.ToString(input), 
                System.Convert.ToString(halfInput));
        }
        catch (System.Exception ex) {
            Console.WriteLine(ex.toString());
        }
    } //CalcHalf2
} //NewExceptionDemo
   
/*
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_JSL.NewExceptionDemo.Half(Int32 input) in C:\Documents
 and Settings
\My Documents\Visual Studio\Projects\ConsoleApp - JS\ConsoleApp
 - JS\Class1.jsl:line 33
   at NDP_UE_JSL.NewExceptionDemo.CalcHalf(Int32 input) in C:\Documents
 and Sett
ings\My Documents\Visual Studio\Projects\ConsoleApp - JS\Consol
eApp - JS\Class1.jsl:line 59

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

Half of 24 is 12.
NDP_UE_JSL.NotEvenException: The argument to a function requiring even input is
not divisible by 2.
   at NDP_UE_JSL.NewExceptionDemo.Half2(Int32 input) in C:\Documents
 and Setting
s\My Documents\Visual Studio\Projects\ConsoleApp - JS\ConsoleAp
p - JS\Class1.jsl:line 46
   at NDP_UE_JSL.NewExceptionDemo.CalcHalf2(Int32 input) in C:\Documents
 and Set
tings\My Documents\Visual Studio\Projects\ConsoleApp - JS\Conso
leApp - JS\Class1.jsl:line 74

*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Exception コンストラクタ (String)

指定したエラー メッセージ使用して、Exception クラス新しインスタンス初期化します。

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

解説解説
使用例使用例

特定の条件Exception派生させるコード例次に示します。この例では、基本 Exception クラス派生クラス両方について、呼び出し元が指定したメッセージパラメータとして受け取コンストラクタ使用方法示します

' Example for the Exception( String ) constructor( String ).
Imports System
Imports Microsoft.VisualBasic

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 ' New
           
        Public Sub New(auxMessage
 As String)
            MyBase.New(String.Format("{0}
 - {1}", _
                auxMessage, notEvenMessage))
        End Sub ' New
    End Class ' NotEvenException

    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 ' Main
           
        ' 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 ' CalcHalf
           
           
        ' 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 ' CalcHalf2

    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)
// Example for the Exception( string ) constructor.
using System;

namespace NDP_UE_CS
{
    // 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.
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.
package NDP_UE_JSL; 

import System.* ;

// Derive an exception with a specifiable message.
class NotEvenException extends System.Exception
{
    private String notEvenMessage = "The argument to a function
 requiring " 
        + "even input is not divisible by 2.";

    public NotEvenException()
    {
        super("The argument to a function requiring " 
            + "even input is not divisible by 2.");
    } //NotEvenException

    public NotEvenException(String auxMessage)
    {
        super(String.Format("{0} - " + "The argument to a function
 requiring " 
            + "even input is not divisible by 2.", auxMessage));
    } //NotEvenException
} //NotEvenException

class NewSExceptionDemo
{
    public static void main(String[]
 args)
    {
        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);
    } //main

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

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

    // 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}.", 
                System.Convert.ToString(input), 
                System.Convert.ToString(halfInput));
        }
        catch (System.Exception ex) {
            Console.WriteLine(ex.toString());
        }
    } //CalcHalf

    // 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}.", 
                System.Convert.ToString(input), 
                System.Convert.ToString(halfInput));
        }
        catch (System.Exception ex) {
            Console.WriteLine(ex.toString());
        }
    } //CalcHalf2
} //NewSExceptionDemo
   
/*
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_JSL.NewSExceptionDemo.Half(Int32 input) in C:\Documents
 and Setting
s\jitesh_chourasia\My Documents\Visual Studio Projects\ConsoleApp - JS\ConsoleAp
p - JS\Class1.jsl:line 47
   at NDP_UE_JSL.NewSExceptionDemo.CalcHalf(Int32 input) in C:\Documents
 and Set
tings\jitesh_chourasia\My Documents\Visual Studio Projects\ConsoleApp - JS\Conso
leApp - JS\Class1.jsl:line 72

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

Half of 30 is 15.
NDP_UE_JSL.NotEvenException: Invalid argument: 33 - The argument to a function r
equiring even input is not divisible by 2.
   at NDP_UE_JSL.NewSExceptionDemo.Half2(Int32 input) in C:\Documents
 and Settin
gs\My Documents\Visual Studio Projects\ConsoleApp - JS\ConsoleApp - JS\
Class1.jsl:line 60
   at NDP_UE_JSL.NewSExceptionDemo.CalcHalf2(Int32 input) in C:\Documents
 and Se
ttings\My Documents\Visual Studio Projects\ConsoleApp - JS\Cons
oleApp - JS\Class1.jsl:line 87
*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Exception コンストラクタ (String, Exception)

指定したエラー メッセージと、この例外原因である内部例外への参照使用して、Exception クラス新しインスタンス初期化します。

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    message As String, _
    innerException As Exception _
)
Dim message As String
Dim innerException As Exception

Dim instance As New Exception(message,
 innerException)
public Exception (
    string message,
    Exception innerException
)
public:
Exception (
    String^ message, 
    Exception^ innerException
)
public Exception (
    String message, 
    Exception innerException
)
public function Exception (
    message : String, 
    innerException : Exception
)

パラメータ

message

例外原因説明するエラー メッセージ

innerException

現在の例外の原因である例外内部例外指定されていない場合は、null 参照 (Visual Basic の場合Nothing)。

解説解説

前の例外直接結果としてスローされる例外については、InnerException プロパティに、前の例外への参照格納されます。InnerException プロパティは、コンストラクタ渡されたものと同じ値を返しますInnerException プロパティによって内部例外値がコンストラクタ渡されなかった場合は、null 参照 (Visual Basic の場合Nothing) を返します

Exceptionインスタンス初期プロパティ値を次の表に示します

使用例使用例

特定の条件Exception派生させるコード例次に示します。この例では、基本 Exception クラス派生クラス両方について、メッセージ内部例外パラメータとして受け取コンストラクタ使用方法示します

' Sample for Exception( String, Exception ) constructor.
Imports System
Imports Microsoft.VisualBasic

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 ' New
           
        Public Sub New(
 auxMessage As String )
            MyBase.New( String.Format( "{0}
 - {1}", _
                overflowMessage, auxMessage ) )
        End Sub ' New
           
        Public Sub New(
 auxMessage As String, inner As
 Exception )
            MyBase.New( String.Format( "{0}
 - {1}", _
                overflowMessage, auxMessage ), inner )
        End Sub ' New
    End Class ' LogTableOverflowException

    Class LogTable
       
        Public Sub New(
 numElements As Integer )
            logArea = New String( numElements
 ) { }
            elemInUse = 0
        End Sub ' New
           
        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 ' LogTable

        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 ' Main

    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()
// 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.
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.
package NDP_UE_JSL; 

import System.* ;

// Derive an exception with a specifiable message and inner exception.
class LogTableOverflowException extends System.Exception
{
    private String overflowMessage = "The log table has overflowed.";

    public LogTableOverflowException()
    {
        super("The log table has overflowed.");
    } //LogTableOverflowException

    public LogTableOverflowException(String auxMessage)
    {
        super(String.Format("The log table has overflowed. - {0}", 
            auxMessage));
    } //LogTableOverflowException

    public LogTableOverflowException(String auxMessage, Exception
 inner)
    {
        super(String.Format("The log table has overflowed.- {0}", auxMessage),
 
            inner);
    } //LogTableOverflowException
} //LogTableOverflowException

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

    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)
 throws LogTableOverflowException
    {
        try {
            logArea.set_Item(elemInUse, newRecord);
            return elemInUse++;
        }
        catch (Exception ex) {
            throw new LogTableOverflowException(String.Format(
                    "Record \"{0}\" was not logged.", newRecord),
 ex);
        }
    } //AddRecord
} //LogTable

class OverflowDemo
{
    // Create a log table and force an overflow.
    public static void main(String[]
 args)
    {
        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 iCtr = 1; ; iCtr++) {
                log.AddRecord(String.Format("Log record number {0}", 
                    System.Convert.ToString(iCtr)));
            }
        }
        catch (System.Exception ex) {
            Console.WriteLine(ex.toString());
        }
    } //main
} //OverflowDemo
 
/*
This example of the Exception( string, Exception )
constructor generates the following output.

Example of a derived exception that references an inner exception:

NDP_UE_JSL.LogTableOverflowException: The log table has overflowed.- 
Record "Log record number 5" was not logged. ---> 
java.lang.ArrayIndexOutOfBoundsException:
 Index was outside the bounds of the array.
   --- End of inner exception stack trace ---
   at NDP_UE_JSL.LogTable.AddRecord(String newRecord) in C:\
Documents and Settings\My Documents\Visual Studio Projects\ConsoleApp - JS\
ConsoleApp - JS\Class1.jsl:line 52
   at NDP_UE_JSL.OverflowDemo.main(String[] args) in C:\Documents
 and Settings\
My Documents\Visual Studio Projects\ConsoleApp - JS\ConsoleApp - JS\
Class1.jsl:line 71
*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Exception コンストラクタ


Exception コンストラクタ (SerializationInfo, StreamingContext)

シリアル化したデータ使用して、Exception クラス新しインスタンス初期化します。

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Protected Sub New ( _
    info As SerializationInfo, _
    context As StreamingContext _
)
Dim info As SerializationInfo
Dim context As StreamingContext

Dim instance As New Exception(info,
 context)
protected Exception (
    SerializationInfo info,
    StreamingContext context
)
protected:
Exception (
    SerializationInfo^ info, 
    StreamingContext context
)
protected Exception (
    SerializationInfo info, 
    StreamingContext context
)
protected function Exception (
    info : SerializationInfo, 
    context : StreamingContext
)

パラメータ

info

スローされている例外に関するシリアル化済みオブジェクト データ保持している SerializationInfo。

context

転送元または転送先に関すコンテキスト情報含んでいる StreamingContext。

例外例外
例外種類条件

ArgumentNullException

info パラメータnull 参照 (Visual Basic では Nothing) です。

SerializationException

クラス名null 参照 (Visual Basic では Nothing) であるか、または HResult が 0 です。

解説解説
使用例使用例

シリアル化できる派生 Exception クラス定義するコード例次に示します。この例では、0 での除算エラー強制し次に ( SerializationInfoStreamingContext ) コンストラクタ使用して派生例外インスタンス作成しますインスタンスファイルシリアル化し、そのファイル新し例外に逆シリアル化して新し例外スローし、その例外データキャッチし表示します

' Example for the Exception( SerializationInfo, StreamingContext )
' constructor and the Exception.GetObjectData( SerializationInfo, 
' StreamingContext ) method.
'
' If compiling with the Visual Basic compiler (VBC) from the command
 
' prompt, be sure to add the following switch:
'    /reference:System.Runtime.Serialization.Formatters.Soap.dll 
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap
Imports Microsoft.VisualBasic
Imports System.Security.Permissions

Namespace NDP_UE_VB

    ' 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 ' New
       
        ' This protected constructor is used for deserialization.
        Protected Sub New(
 info As SerializationInfo, _
            context As StreamingContext )
                MyBase.New( info, context )
        End Sub ' New
           
           
        ' 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.ToUpper()
              
            MyBase.GetObjectData(info, context)

        End Sub ' ISerializable.GetObjectData
    End Class ' SecondLevelException


    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 ' Main

    End Module ' SerializationDemo
End Namespace ' NDP_UE_VB

' 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
' 
' 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()
// Example for the Exception( SerializationInfo, StreamingContext )
// constructor and the Exception.GetObjectData( SerializationInfo, 
// StreamingContext ) method.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security.Permissions;

namespace NDP_UE_CS
{
    // 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.
        [SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
        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.ToUpper( );

            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 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

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()
*/
// Example for the Exception( SerializationInfo, StreamingContext )
// constructor and the Exception.GetObjectData( SerializationInfo, 
// StreamingContext ) method.
#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->ToUpper();
      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()

*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Exception プロパティ


Exception メソッド


パブリック メソッドパブリック メソッド

プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Exception クラス
System 名前空間
SystemException
ApplicationException クラス

その他の技術情報

例外の処理とスロー
リソースパッケージ化配置

Exception メンバ

アプリケーションの実行中に発生するエラー表します

Exception データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
プロテクト コンストラクタプロテクト コンストラクタ
パブリック プロパティパブリック プロパティ
プロテクト プロパティプロテクト プロパティ
  名前 説明
プロテクト プロパティ HResult 特定の例外割り当てられているコード化数値である HRESULT を取得または設定します
パブリック メソッドパブリック メソッド
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Exception クラス
System 名前空間
SystemException
ApplicationException クラス

その他の技術情報

例外の処理とスロー
リソースパッケージ化配置

_Exception インターフェイス

メモ : このインターフェイスは、.NET Framework version 2.0新しく追加されたものです。

System.Exception クラスパブリック メンバアンマネージ コード公開します

 

名前空間: System.Runtime.InteropServices
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)> _
<CLSCompliantAttribute(False)> _
<ComVisibleAttribute(True)> _
<GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")>
 _
Public Interface _Exception
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] 
[CLSCompliantAttribute(false)] 
[ComVisibleAttribute(true)] 
[GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")] 
public interface _Exception
[InterfaceTypeAttribute(ComInterfaceType::InterfaceIsDual)] 
[CLSCompliantAttribute(false)] 
[ComVisibleAttribute(true)] 
[GuidAttribute(L"b36b5c63-42ef-38bc-a07e-0b34c98f164a")] 
public interface class _Exception
/** @attribute InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual) */ 
/** @attribute CLSCompliantAttribute(false) */ 
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a") */
 
public interface _Exception
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual) 
CLSCompliantAttribute(false) 
ComVisibleAttribute(true) 
GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a") 
public interface _Exception
解説解説
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
_Exception メンバ
System.Runtime.InteropServices 名前空間
System.Exception

_Exception プロパティ


_Exception メソッド


_Exception メンバ

System.Exception クラスパブリック メンバアンマネージ コード公開します

_Exception データ型公開されるメンバを以下の表に示します


パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
参照参照

関連項目

_Exception インターフェイス
System.Runtime.InteropServices 名前空間
System.Exception




固有名詞の分類

このページでは「.NET Framework クラス ライブラリ リファレンス」からExceptionを検索した結果を表示しています。
Weblioに収録されているすべての辞書からExceptionを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からExceptionを検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Exception」の関連用語

Exceptionのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Exceptionのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS