exception
「exception」の意味
「exception」とは、例外や除外を意味する英単語である。一般的なルールやパターンから外れる事象や状況を指す場合に使用される。また、特定の対象を除外することを示す際にも用いられる。具体的には、プログラミングにおけるエラー処理や、特定の条件下でのみ適用される規則など、様々な文脈で使用される。「exception」の発音・読み方
「exception」の発音は、/ɪkˈsɛpʃən/であり、カタカナ表記では「イクセプション」となる。日本人が発音するカタカナ英語では、「エクセプション」と読むことが一般的である。発音によって意味や品詞が変わる単語ではないため、特別な注意は必要ない。「exception」の定義を英語で解説
An exception is a person or thing that is excluded from a general statement or does not follow a rule. It can also refer to the act of excluding something or someone from a particular rule, order, or standard. In programming, an exception is an event that occurs when an error or other exceptional condition arises during the execution of a program.「exception」の類語
「exception」の類語には、anomaly(異常)、deviation(逸脱)、irregularity(不規則性)、exclusion(除外)などがある。これらの単語も、ある基準や規則から外れる事象や状況を指す際に使用されるが、ニュアンスや文脈によって使い分けられる。「exception」に関連する用語・表現
「exception」に関連する用語や表現には、exception handling(例外処理)、exceptional case(特殊なケース)、exception to the rule(規則の例外)、without exception(例外なく)などがある。これらの表現は、例外や特別な状況を扱う際に用いられる。「exception」の例文
1. There are no exceptions to this rule.(この規則には例外はない。)2. She is an exception to the general trend.(彼女は一般的な傾向から外れている。)
3. The manager made an exception for him.(マネージャーは彼に対して例外を許した。)
4. This case is an exception to our usual policy.(このケースは、私たちの通常の方針から外れている。)
5. Exception handling is an important aspect of programming.(例外処理はプログラミングの重要な側面である。)
6. The software detects exceptions and generates error messages.(ソフトウェアは例外を検出し、エラーメッセージを生成する。)
7. The system will automatically exclude any exceptions.(システムは自動的に例外を除外する。)
8. This is an exceptional case and should not be considered as a precedent.(これは特別なケースであり、先例として考慮すべきではない。)
9. All employees must follow the dress code without exception.(すべての従業員は例外なくドレスコードに従わなければならない。)
10. The new policy will be applied to all projects, with no exceptions.(新しい方針はすべてのプロジェクトに例外なく適用される。)
Exception クラス
アセンブリ: 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

このクラスは、すべての例外の基本クラスです。エラーが発生すると、システムまたは現在実行中のアプリケーションは、そのエラーに関する情報が格納された例外をスローすることによりエラーをレポートします。スローされた例外は、アプリケーションまたは既定の例外ハンドラによって処理されます。
共通言語ランタイムは、オブジェクトとして例外の表現に基づく例外処理モデルを提供し、また、プログラム コードと例外処理コードをそれぞれ 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 ブロックが見つからずにコール スタックの最上位レベルに達した場合は、既定の例外ハンドラがその例外を処理し、アプリケーションが終了します。
-
ユーザーが判読できる、エラーを説明したテキスト。例外が発生すると、ランタイムはテキスト メッセージを提供して、ユーザーにエラーの性質を通知したり、問題を解決する処置のヒントを与えます。このテキスト メッセージは、例外オブジェクトの Message プロパティに保持されます。例外オブジェクトの作成時に、その特定の例外の詳細を説明するテキスト文字列をコンストラクタに渡すことができます。コンストラクタに渡すエラー メッセージの引数を指定しない場合は、既定のエラー メッセージが使用されます。
-
例外がスローされたときのコール スタックの状態。StackTrace プロパティには、コード内のエラー発生箇所を判断するために使用できるスタック トレースが保持されています。スタック トレースは、呼び出されたすべてのメソッドと、呼び出しを行うソース ファイル内の行番号の一覧を表示します。
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 ブロックを示すコード例は、次のとおりです。DivideByZeroException は ArithmeticException から派生し、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



Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Exception コンストラクタ ()
アセンブリ: mscorlib (mscorlib.dll 内)


このコンストラクタは、新しいインスタンスの Message プロパティを初期化して、その値として、現在のシステムのカルチャを反映した、エラーを説明するシステム提供のメッセージを指定します。
すべての派生クラスにこの既定のコンストラクタを用意することをお勧めします。Exception のインスタンスの初期プロパティ値を次の表に示します。

定義済みのメッセージを使用する 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 */

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Exception コンストラクタ (String)
アセンブリ: 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 */

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Exception コンストラクタ (String, Exception)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim message As String Dim innerException As Exception Dim instance As New Exception(message, innerException)

前の例外の直接の結果としてスローされる例外については、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 */

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Exception コンストラクタ

名前 | 説明 |
---|---|
Exception () | Exception クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |
Exception (String) | 指定したエラー メッセージを使用して、Exception クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |
Exception (SerializationInfo, StreamingContext) | シリアル化したデータを使用して、Exception クラスの新しいインスタンスを初期化します。 |
Exception (String, Exception) | 指定したエラー メッセージと、この例外の原因である内部例外への参照を使用して、Exception クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |

Exception コンストラクタ (SerializationInfo, StreamingContext)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim info As SerializationInfo Dim context As StreamingContext Dim instance As New Exception(info, context)



シリアル化できる派生 Exception クラスを定義するコード例を次に示します。この例では、0 での除算エラーを強制し、次に ( SerializationInfo、StreamingContext ) コンストラクタを使用して派生例外のインスタンスを作成します。インスタンスをファイルにシリアル化し、そのファイルを新しい例外に逆シリアル化して新しい例外をスローし、その例外のデータをキャッチして表示します。
' 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() */

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Exception プロパティ

名前 | 説明 | |
---|---|---|
![]() | Data | 例外に関する追加のユーザー定義情報を提供するキー/値ペアのコレクションを取得します。 |
![]() | HelpLink | 例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。 |
![]() ![]() ![]() | Source | エラーの原因となったアプリケーションまたはオブジェクトの名前を取得または設定します。 |
![]() ![]() | TargetSite | 現在の例外をスローするメソッドを取得します。 |


Exception メソッド

名前 | 説明 | |
---|---|---|
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。) |
![]() | GetBaseException | 派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の主要な原因である Exception を返します。 |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。) |
![]() | GetObjectData | 派生クラスでオーバーライドされた場合は、その例外に関する情報を使用して SerializationInfo を設定します。 |
![]() | GetType | 現在のインスタンスのランタイム型を取得します。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。) |
![]() | ToString | オーバーライドされます。 現在の例外の文字列形式を作成して返します。 |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 ( Object から継承されます。) |

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



名前 | 説明 | |
---|---|---|
![]() | Data | 例外に関する追加のユーザー定義情報を提供するキー/値ペアのコレクションを取得します。 |
![]() | HelpLink | 例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。 |
![]() ![]() ![]() | Source | エラーの原因となったアプリケーションまたはオブジェクトの名前を取得または設定します。 |
![]() ![]() | TargetSite | 現在の例外をスローするメソッドを取得します。 |


名前 | 説明 | |
---|---|---|
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。) |
![]() | GetBaseException | 派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の主要な原因である Exception を返します。 |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。) |
![]() | GetObjectData | 派生クラスでオーバーライドされた場合は、その例外に関する情報を使用して SerializationInfo を設定します。 |
![]() | GetType | 現在のインスタンスのランタイム型を取得します。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。) |
![]() | ToString | オーバーライドされます。 現在の例外の文字列形式を作成して返します。 |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 (Object から継承されます。) |

_Exception インターフェイス
アセンブリ: 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

このインターフェイスは、アンマネージ コードからマネージ クラスにアクセスするためのインターフェイスであるため、マネージ コードからは呼び出さないでください。
このインターフェイスでは、アンマネージ COM オブジェクトでアクセス可能な System.Exception クラス メンバの vtable の順序が保持されます。

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


_Exception プロパティ

名前 | 説明 | |
---|---|---|
![]() | HelpLink | COM オブジェクトに、Exception.HelpLink プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | InnerException | COM オブジェクトに、Exception.InnerException プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | Message | COM オブジェクトに、Exception.Message プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | Source | COM オブジェクトに、Exception.Source プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | StackTrace | COM オブジェクトに、Exception.StackTrace プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | TargetSite | COM オブジェクトに、Exception.TargetSite プロパティへのバージョンに依存しないアクセスが用意されています。 |

_Exception メソッド

名前 | 説明 | |
---|---|---|
![]() | Equals | COM オブジェクトに、Object.Equals メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetBaseException | COM オブジェクトに、Exception.GetBaseException メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetHashCode | COM オブジェクトに、Object.GetHashCode メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetObjectData | COM オブジェクトに、Exception.GetObjectData メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetType | COM オブジェクトに、Exception.GetType メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | ToString | COM オブジェクトに、Exception.ToString メソッドへのバージョンに依存しないアクセスが用意されています。 |

_Exception メンバ
System.Exception クラスのパブリック メンバをアンマネージ コードに公開します。
_Exception データ型で公開されるメンバを以下の表に示します。

名前 | 説明 | |
---|---|---|
![]() | HelpLink | COM オブジェクトに、Exception.HelpLink プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | InnerException | COM オブジェクトに、Exception.InnerException プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | Message | COM オブジェクトに、Exception.Message プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | Source | COM オブジェクトに、Exception.Source プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | StackTrace | COM オブジェクトに、Exception.StackTrace プロパティへのバージョンに依存しないアクセスが用意されています。 |
![]() | TargetSite | COM オブジェクトに、Exception.TargetSite プロパティへのバージョンに依存しないアクセスが用意されています。 |

名前 | 説明 | |
---|---|---|
![]() | Equals | COM オブジェクトに、Object.Equals メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetBaseException | COM オブジェクトに、Exception.GetBaseException メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetHashCode | COM オブジェクトに、Object.GetHashCode メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetObjectData | COM オブジェクトに、Exception.GetObjectData メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | GetType | COM オブジェクトに、Exception.GetType メソッドへのバージョンに依存しないアクセスが用意されています。 |
![]() | ToString | COM オブジェクトに、Exception.ToString メソッドへのバージョンに依存しないアクセスが用意されています。 |

例外
![]() | この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。(2016年11月) |
例外(れいがい、英: exception[1][2])とは、通例の原則にあてはまっていないこと[3]。一般の原則の適用を受けないこと[3]。
概説
例外とは通例の原則にあてはまっていないこと[3]。また、一般の原則の適用を受けないことである。
たとえば法則(や規則)が成り立っていない事例のこと。あるいは、法則がそもそも適用されていないもののこと。
「例外のない法則はない」「例外のない規則はない」などと言われることがある。[注 1] つまり規則や法則には例外がつきものではある。
対比される概念は「原則」である。
法律と例外
法律論では、「何が原則で、何が例外だ」という議論のしかたをすることが多くある[4]。いつでも一定の原則だけで例外がない、ということは滅多に無い[4]。大抵のケースで、原則が多くの場合に適用されるものの、例外的に原則が適用されない場合がある、ということになる[4]。
よって、まずどのような場合に対してどのような原則があるかを明らかにし、その次に、その原則の例外はどのようになるか(どのように扱うか)を明らかにする、というのが法律論の一般的なパターンである[4]。
(これは単に法律論にとどまるものではなく)法律の条文や、契約書の条項も、こうした法律論のパターンに合わせた形で書かれていることが一般的である[4]。よって、法律や契約書もこれを意識しながら読むと、正しく理解できる[4]。
たとえば、契約書の場合について解説してみる[4]。例をひとつ挙げる。
売主は本商品を来年3月31日までに引き渡すものとする。但し売主の責任によらず商品が完成できない特別な事情がある場合には、この限りではない。[4]
この契約では、
原則は、3月31日が引き渡し期限となっている[4]。
例外としては、売主に落ち度が無い特別な事情が生じた場合は(例えば戦争や巨大災害などで材料の調達が不可能になったり、工場が破壊されてしまった場合などは)、売主は3月31日までに引き渡す義務は負わない、ということを言っている[4]。
契約書の例外は「但し」という言葉以降に書かれていることが多い。 (そのため、例外に関する記述を「但し書き(ただしがき)」とも言う。)
《原則》と《例外》の話は、実体法のレベルだけで現れるわけではない[4]。手続き法のレベルでも現れる[4]。
法律をよく知らずに法律を読む人(たとえば特定の筋書きのある小説や、理念表明などのように読もうとする人など)は「結論はどちらだ? 結論がはっきりしない。」とか「法律は面倒だ。」などと感想を漏らすことがある[4]。
では、なぜ(複雑になるのに)法律には一般に「原則」と「例外」があるのかと言うと、人間社会の事象というのは、ケースバイケースであり、一律にどちらかとは決められないからである[4]。ケースバイケースであるから複雑になりはするが、そうしたやりかたで決めるからこそ、社会正義に則した妥当な結論を導ける、という面があるのである[4]。
例外的な状態を意図的に狙うもの、いわゆる「法律の網をかいくぐる」ような者が現れることがある。それが度を超し常態化すると、法律があっても機能していない、意味が無い、という状態になってしまうこともある。
例外には「歯止め」を設定する場合もある。たとえば道路交通法は緊急自動車をその例外に認めている。その有益性は明らかであろう。しかしたとえば警察車両であれば無条件でこれを認めるのではなく、警告灯やサイレンをならすことを義務づけている。
自然科学と例外
生物学の分野では例外は多い。メンデルの法則は身近な動植物ですらむしろきれいに当てはまるものを探すのが難しく、生物全体を見れば、直接当てはめることすらできない例も多い。そもそもメンデル自身、自説を発表する際、予備実験として多くの形質について実験を行っており、その中から法則性を示せる形質のみを取り上げているが、その際に取り上げた形質の数より捨てた形質の数の方が多い。しかしメンデルの法則は生物学の分野ではむしろよく整えられた法則である。
生物学の歴史を見れば、非常に多くの法則が提唱されては消えている。それらの多くは確かに当てはまる例はいくつもあるにせよ、当てはまらないものの方が多いんじゃないか、というものもある。そのため、その多くは「○○の場合、××となることが多い」といった言い方で示されている。中には「生物に関してあるアイデアを思いついた場合、それの裏付けとなる生物は必ず存在する」という声ある。たとえば1921年にペトロニヴィクスは「種・系統樹および群の進化の法則」と題して24の法則を総括している(井尻正二『化石』岩波新書,1968)が、この中には1:放散の法則(→適応放散)、7:収斂の法則(→収斂進化)のように、現在でも認められるもののそれを法則とは呼ばないようなものばかりである。
現代物理学においては、物事を数的に(量で)表現し、数学を用いて把握しようとする。だが、数学は形式科学なので、自然科学とは異なり、数学だけでは自然については何も言うことができない。どのような関係にあるのか、というのは、実際に確かめて(=実験)してから判断し、実際に確かめる前に推察でうかつなことを言ってしまうのは避ける、とするのが自然科学である。また、ある時、ある数式を思いつきおおむねその数式に沿って自然が動いているようだ、と考えられるようになっても、だからといっていつでも数式通りに自然が動くだろう、などと期待したり、絶対に数式どおりに自然は動くはずだ、と決めつけるのは自然科学的には不適切である。いつも疑う態度を保ち、実際に確かめ続けるのが自然科学的態度である。
なお、「振り子の等時性」は古くから言われているが、実は「振り子は、いつも等時的に動いている」と見なしてよいのか、(ガリレオなどの物理学者が、物を基準に時間を計る、と恣意的に決めて)「ある(同一の)振り子が1回振れる間を、同じ時間と見なす」と方針を定めて理論体系を組み立てたのか、つきつめて科学哲学的に考察する場合、難しい問題をはらんでいる。例えば冬至の日の出から日の出の間に揺れる振り子の回数を観測してみた場合に、それがある年に増えた場合に、「1日の長さが伸びたのか?」(「地球の回転の速度が遅くなったのか?」)と考えるのか、「昨年と比べて振り子の1回の揺れにかかる時間が短くなったのか?」というのは、この観測だけでは解決できない。ほかの様々な観察をいくつも行い、総合的に判断せざるを得ない。ひとつの振り子だけを用いている場合でも複雑であるが、複数の振り子、あるいは周期的な運動を「時計」として用いている時に、それぞれが「ズレ」た場合、それが何を意味しているのか解釈する場合も、実は複雑になる。
あらかじめ想定している法則にあてはまらない事例が見つかった場合、どう判断するのか、という難しいテーマがある。
- 「観測のミス」「実験のミス」と見なし、観測や実験のやり直しを行うか
- つまらないこと、と感じて、無視したり、記憶から消してしまうのか
- 別の法則を新たに付け足してでも、強引に理論体系を守ろうとするのか(アドホックな仮説)
- (「これを認めたら、結局、法則は無い、ということになってしまう」「都合が悪い」などと感じて)データを意図的に無視して隠ぺいしたり、改ざんして、インチキ論文を書いてしまうか(科学における不正行為)
- 法則が成り立たない範囲、「例外」「特異点」を発見したのか検討し、そうだった場合に、それの活用を探るのか(セレンディピティ)
同じ事象を眼の前にして、どのような判断・行動をするのか、ということで結果が大きく異なってくる。
数学と例外
数学の四則演算の場合、任意の二つの数の間でどの演算もできるし、どの場合も答えは一つ求められる。しかし、0で除算することだけはこの例外である。この場合、例外は明らかにこの一つだけである。
数学においては、命題(全称命題)にひとつの例外をあげることができれば、その命題は正しくないと判断する。その場合は例外とは言わず、反例という。
その数があまりにも少なく、またそれを取り除いた範囲でのその命題の正しさが証明できるのであれば、例外をあらかじめ明記する形で命題を記述する方法もある。
コンピュータと例外
プログラミングでは、プログラムがある処理を実行している途中で生じ得る、設計から逸脱した状態を「例外」という。プログラムの利用者が対処するエラーとは異なり、例外は開発者が対処する。例外発生時にはプログラムにより実現されるシステムの内部状態に矛盾が生じており、適切に対処されなければ以後の処理継続が不可能になるか、処理が継続できても破壊的な処理が進行してしまう可能性が高い。設計上無視する場合は問題にならないが、例外の見落としは重大なシステム障害に繋がる。システムが正常な内部状態を保つためには、開発者により全ての例外への対処が設計されていなければならない。
例えば次のような状態である。
- 0で除算しなければならない状況になる
- 存在しないファイルを読み書きしようとする
- データベースに重複したキーのレコードを挿入しようとする
例外が発生した場合に、現在の処理を中断(中止)して別の処理や回避処理を行うことを例外処理という。
プログラミング言語としては、C++、C#、Visual Basic.NET、Java、Pythonなどが例外機構を備えている。Javaでは例外が生じた場合の処理のしかたをあらかじめ記述することで、処理が全体として破綻しないようにすることができる。(例外が起こりうる処理をtry
ブロックに記述し、続くcatch
ブロックに、想定する例外とそれらに対する処理を記述しておくことができる)
Windowsでのブルースクリーンが表示される「例外0E」なども例外にあたる。
また、CPUが0での除算などの実行できない処理に遭遇することについても言う。UNIX系 OS で「ハードウェア例外」が発生すると、カーネルはプロセスに対してSIGFPEやSIGSEGVなどのシグナルを生成する。
自然言語と例外
自然言語の文法にも例外があり、自然言語の語法にも例外がある。
不規則活用
自然言語のいくつかの語彙に対して(その自然言語における)規則的な活用を見出すことができる。しかし一般的にはすべての語彙に適用できる規則はなく、その規則に当てはまらない例外が存在する。
例えば(現代)英語の不規則動詞はおよそ 200 語とされ[5]、その他の動詞はすべて規則的であると考えられている[注 2]。
英語における動詞の規則活用は、原形に対し末尾に "-ed" を付加して過去形および過去分詞形を表すものである。規則動詞として例えば以下のものが挙げられる:
原形 | 過去形 | 過去分詞形 |
---|---|---|
open | opened | opened |
try | tried | tried |
share | shared | shared |
submit | submitted | submitted |
beg | begged | begged |
これらの規則動詞と異なる活用をする動詞を不規則動詞という。不規則動詞の例として以下が挙げられる:
原形 | 過去形 | 過去分詞形 |
---|---|---|
catch | caught | caught |
write | wrote | written |
read | read | read |
go | went | gone |
see | saw | seen |
近現代の英語における不規則活用の多くは、それ以前の古い時代の活用が残ったものと考えられている。
用法
- 例外中の例外
- 例外であることを強調する表現。「極めて異例」という意味で使われることもある。
- 例外的に認める
- 今回限りの特別な措置により認めるという意味合いで使われる。
- 例外の国
- 国ではないが、他の国との比較で国として扱う方が都合が良い地域。南極。
例外のパラドックス
例外のパラドックスは、嘘つきのパラドックスやラッセルのパラドックスに似たパラドックスで、『例外のない規則はない』という規則たる命題を仮定し、その命題に対して
- 例外があると仮定すると、「例外のない規則がある」ということになり、矛盾する。
- 例外がないと仮定すると、元の命題に反する。
このように、例外のない規則に例外があると仮定してもないと仮定しても自己矛盾してしまう。ゆえに、元の命題自体が偽である(つまり、狭義のパラドックスではない)。そこで、『例外のパラドックスはこの法則自体にも適用できる』と付け足す例もあるが、付け足したとしても元の命題を真にすることはできないため、これはナンセンスである。
注釈
- ^ この法則自体にも適用できる、と付け足す例もある、詳しくは下記参照)。
- ^ なお現代英語として一般的に通用する動詞の数は、動詞の数え方に依存しているため具体的に定められないが、例えばオックスフォード英語辞典に収録されている語彙としてはおよそ25000 語[6]である。
出典
関連項目
固有名詞の分類
- exceptionのページへのリンク