Exception クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
アプリケーションの実行中に発生したエラーを表します。
public ref class Exception
public ref class Exception : System::Runtime::Serialization::ISerializable
public ref class Exception : System::Runtime::InteropServices::_Exception, System::Runtime::Serialization::ISerializable
public class Exception
public class Exception : System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public class Exception : System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public class Exception : System.Runtime.Serialization.ISerializable
type Exception = class
type Exception = class
interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
type Exception = class
interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Exception = class
interface ISerializable
interface _Exception
[<System.Serializable>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Exception = class
interface ISerializable
Public Class Exception
Public Class Exception
Implements ISerializable
Public Class Exception
Implements _Exception, ISerializable
- 継承
-
Exception
- 派生
- 属性
- 実装
例
次の例では、エラーをcatch
処理ArithmeticExceptionするために定義された (with
F#の) ブロックを示します。 エラーに対DivideByZeroExceptionして明示的に定義されたブロックがないためArithmeticExceptionDivideByZeroException、このcatch
ブロックはcatch
エラーもキャッチDivideByZeroExceptionします。
using namespace System;
int main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch ( ArithmeticException^ e )
{
Console::WriteLine( "ArithmeticException Handler: {0}", e );
}
catch ( Exception^ e )
{
Console::WriteLine( "Generic Exception Handler: {0}", e );
}
}
/*
This code example produces the following results:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at main()
*/
using System;
class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch (ArithmeticException e)
{
Console.WriteLine($"ArithmeticException Handler: {e}");
}
catch (Exception e)
{
Console.WriteLine($"Generic Exception Handler: {e}");
}
}
}
/*
This code example produces the following results:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at ExceptionTestClass.Main()
*/
module ExceptionTestModule
open System
let x = 0
try
let y = 100 / x
()
with
| :? ArithmeticException as e ->
printfn $"ArithmeticException Handler: {e}"
| e ->
printfn $"Generic Exception Handler: {e}"
// This code example produces the following results:
// ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
// at <StartupCode$fs>.$ExceptionTestModule.main@()
Class ExceptionTestClass
Public Shared Sub Main()
Dim x As Integer = 0
Try
Dim y As Integer = 100 / x
Catch e As ArithmeticException
Console.WriteLine("ArithmeticException Handler: {0}", e.ToString())
Catch e As Exception
Console.WriteLine("Generic Exception Handler: {0}", e.ToString())
End Try
End Sub
End Class
'
'This code example produces the following results:
'
'ArithmeticException Handler: System.OverflowException: Arithmetic operation resulted in an overflow.
' at ExceptionTestClass.Main()
'
注釈
このクラスは、すべての例外の基本クラスです。 エラーが発生すると、システムまたは現在実行中のアプリケーションのいずれかが、エラーに関する情報を含む例外をスローして報告します。 例外がスローされると、アプリケーションまたは既定の例外ハンドラーによって処理されます。
このセクションの内容は次のとおりです。
エラーと例外
Try/catch ブロック
例外の種類の機能
例外クラスのプロパティ
パフォーマンスに関する考慮事項
例外を再スローする
標準例外の選択
カスタム例外の実装
エラーと例外
実行時エラーは、さまざまな理由で発生する可能性があります。 ただし、すべてのエラーをコード内の例外として処理する必要はありません。 実行時に発生する可能性があるエラーのカテゴリと、それらに対応するための適切な方法を次に示します。
使用状況エラー。 使用エラーは、例外が発生する可能性があるプログラム ロジックのエラーを表します。 ただし、エラーに対処するには、例外処理ではなく、エラーのあるコードを変更する必要があります。 たとえば、次の例のメソッドの Object.Equals(Object) オーバーライドでは、引数は常に
obj
null 以外である必要があることを前提としています。using System; public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { // This implementation contains an error in program logic: // It assumes that the obj argument is not null. Person p = (Person) obj; return this.Name.Equals(p.Name); } } public class Example { public static void Main() { Person p1 = new Person(); p1.Name = "John"; Person p2 = null; // The following throws a NullReferenceException. Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); } }
// In F#, null is not a valid state for declared types // without 'AllowNullLiteralAttribute' [<AllowNullLiteral>] type Person() = member val Name = "" with get, set override this.GetHashCode() = this.Name.GetHashCode() override this.Equals(obj) = // This implementation contains an error in program logic: // It assumes that the obj argument is not null. let p = obj :?> Person this.Name.Equals p.Name let p1 = Person() p1.Name <- "John" let p2: Person = null // The following throws a NullReferenceException. printfn $"p1 = p2: {p1.Equals p2}"
Public Class Person Private _name As String Public Property Name As String Get Return _name End Get Set _name = value End Set End Property Public Overrides Function Equals(obj As Object) As Boolean ' This implementation contains an error in program logic: ' It assumes that the obj argument is not null. Dim p As Person = CType(obj, Person) Return Me.Name.Equals(p.Name) End Function End Class Module Example Public Sub Main() Dim p1 As New Person() p1.Name = "John" Dim p2 As Person = Nothing ' The following throws a NullReferenceException. Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module
NullReferenceExceptionオーバーライドを呼び出Object.Equalsしてから再コンパイルする前に、ソース コードを変更して null を明示的にテストすることで、発生
obj``null
する例外を排除できます。 次の例には、引数を処理する修正されたソース コードがnull
含まれています。using System; public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode() { return this.Name.GetHashCode(); } public override bool Equals(object obj) { // This implementation handles a null obj argument. Person p = obj as Person; if (p == null) return false; else return this.Name.Equals(p.Name); } } public class Example { public static void Main() { Person p1 = new Person(); p1.Name = "John"; Person p2 = null; Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); } } // The example displays the following output: // p1 = p2: False
// In F#, null is not a valid state for declared types // without 'AllowNullLiteralAttribute' [<AllowNullLiteral>] type Person() = member val Name = "" with get, set override this.GetHashCode() = this.Name.GetHashCode() override this.Equals(obj) = // This implementation handles a null obj argument. match obj with | :? Person as p -> this.Name.Equals p.Name | _ -> false let p1 = Person() p1.Name <- "John" let p2: Person = null printfn $"p1 = p2: {p1.Equals p2}" // The example displays the following output: // p1 = p2: False
Public Class Person Private _name As String Public Property Name As String Get Return _name End Get Set _name = value End Set End Property Public Overrides Function Equals(obj As Object) As Boolean ' This implementation handles a null obj argument. Dim p As Person = TryCast(obj, Person) If p Is Nothing Then Return False Else Return Me.Name.Equals(p.Name) End If End Function End Class Module Example Public Sub Main() Dim p1 As New Person() p1.Name = "John" Dim p2 As Person = Nothing Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) End Sub End Module ' The example displays the following output: ' p1 = p2: False
使用エラーに対して例外処理を使用する代わりに、このメソッドを Debug.Assert 使用してデバッグ ビルドの使用状況エラーを識別し、デバッグ ビルドと Trace.Assert リリース ビルドの両方で使用状況エラーを識別するメソッドを使用できます。 詳細については、「マネージド コードのアサーション」を参照してください。
プログラム エラー。 プログラム エラーは実行時エラーであり、バグのないコードを記述することで必ずしも回避することはできません。
場合によっては、プログラム エラーに予期されるエラーまたはルーチン エラー状態が反映される場合があります。 この場合は、例外処理を使用してプログラム エラーに対処しないようにし、代わりに操作を再試行することをお勧めします。 たとえば、ユーザーが特定の形式で日付を入力することが予想される場合は、メソッドを呼び出すことで日付文字列を解析できます。このメソッドを呼び出DateTime.TryParseExactすと、メソッドを使用DateTime.ParseExactする代わりに解析操作が成功したかどうかを示す値が返Booleanされ、日付文字列を値にDateTime変換できない場合は例外がスローFormatExceptionされます。 同様に、ユーザーが存在しないファイルを開こうとすると、最初にメソッドを File.Exists 呼び出してファイルが存在するかどうかを確認し、存在しない場合は、作成するかどうかをユーザーに求めることができます。
それ以外の場合、プログラム エラーには、コードで処理できる予期しないエラー条件が反映されます。 たとえば、ファイルが存在するかどうかを確認した場合でも、ファイルを開く前に削除されたり、破損したりする可能性があります。 その場合、オブジェクトをインスタンス化するか、メソッドを呼び出してファイルをStreamReader開こうとすると、例外がOpenFileNotFoundExceptionスローされる可能性があります。 このような場合は、例外処理を使用してエラーから回復する必要があります。
システムエラー。 システム エラーは、プログラムで意味のある方法で処理できない実行時エラーです。 たとえば、共通言語ランタイムが追加のメモリを OutOfMemoryException 割り当てることができない場合、どのメソッドでも例外をスローできます。 通常、システムエラーは例外処理を使用して処理されません。 代わりに、このような AppDomain.UnhandledException イベントを使用してメソッドを呼び出 Environment.FailFast して例外情報をログに記録し、アプリケーションが終了する前にエラーをユーザーに通知することができます。
Try/catch ブロック
共通言語ランタイムは、例外をオブジェクトとして表現し、プログラム コードと例外処理コードをブロックとcatch
ブロックに分離した例外処理モデルをtry
提供します。 1 つ以上 catch
のブロックがあり、それぞれが特定の種類の例外を処理するように設計されているか、別のブロックよりも特定の例外をキャッチするように設計された 1 つのブロックがあります。
アプリケーション がアプリケーション コードのブロックの実行中に発生する例外を処理する場合、コードはステートメント内 try
に配置する必要があり、ブロックと呼ばれます try
。 ブロックによってスローされる例外を try
処理するアプリケーション コードは、ステートメント内に catch
配置され、ブロックと呼ばれます catch
。 0 個以上 catch
のブロックがブロックに関連付 try
けられています。各 catch
ブロックには、処理する例外の種類を決定する型フィルターが含まれています。
ブロックでtry
例外が発生すると、システムは、例外を処理するブロックが見つかるcatch
まで、アプリケーション コードに表示される順序で関連catch
するブロックを検索します。 catch
catch ブロックの型T
フィルターが指定T
されているか、派生元の型である場合、ブロックは型の例外をT
処理します。 例外を処理する最初 catch
のブロックが見つかると、システムは検索を停止します。 このため、アプリケーション コードでは、このセクションに続く例で示すように、 catch
型を処理するブロックを、その基本型を処理するブロックの前 catch
に指定する必要があります。 処理する catch ブロックが最後に System.Exception
指定されます。
現在try
のブロックにcatch
関連付けられているブロックのいずれも例外を処理し、現在のブロックが現在try
の呼び出しの他try
のブロック内に入れ子になっている場合、次のcatch
外側try
のブロックに関連付けられているブロックが検索されます。 例外のブロックが見つからない catch
場合、システムは現在の呼び出しで以前の入れ子レベルを検索します。 現在の呼び出しで例外のブロックが見つからない catch
場合は、例外が呼び出し履歴に渡され、前のスタック フレームで例外を処理するブロックが検索されます catch
。 呼び出し履歴の検索は、例外が処理されるまで、または呼び出し履歴にこれ以上フレームが存在しないまで続行されます。 例外を処理するブロックが見つ catch
からずに呼び出し履歴の先頭に到達すると、既定の例外ハンドラーによって処理され、アプリケーションが終了します。
F# try..with Expression
F# ではブロックは使用 catch
されません。 代わりに、発生した例外は、1 つの with
ブロックを使用してパターンが一致します。 これはステートメントではなく式であるため、すべてのパスは同じ型を返す必要があります。 詳細については、「 Try..」を参照してください。式を使用します。
例外の種類の機能
例外の種類では、次の機能がサポートされています。
エラーを説明する人間が判読できるテキスト。 例外が発生すると、ランタイムは、エラーの性質をユーザーに通知し、問題を解決するためのアクションを提案するテキスト メッセージを使用できるようにします。 このテキスト メッセージは、例外オブジェクトのプロパティに Message 保持されます。 例外オブジェクトの作成時に、テキスト文字列をコンストラクターに渡して、その特定の例外の詳細を記述できます。 コンストラクターにエラー メッセージ引数が指定されていない場合は、既定のエラー メッセージが使用されます。 詳細については、Message プロパティを参照してください。
例外がスローされたときの呼び出し履歴の状態。 このプロパティには StackTrace 、コード内でエラーが発生する場所を特定するために使用できるスタック トレースが含まれています。 スタック トレースには、呼び出し元のすべてのメソッドと、呼び出しが行われるソース ファイル内の行番号が一覧表示されます。
例外クラスのプロパティ
このExceptionクラスには、コードの場所、型、ヘルプ ファイル、および例外の理由を識別するのに役立つ多数のプロパティが含まれています。 MessageStackTraceInnerExceptionHelpLinkHResultSourceTargetSiteData
2 つ以上の例外の間に因果関係が存在する場合、 InnerException プロパティはこの情報を保持します。 外側の例外は、この内部例外に応答してスローされます。 外部例外を処理するコードでは、前の内部例外の情報を使用して、エラーをより適切に処理できます。 例外に関する補足情報は、プロパティ内のキーと値のペア Data のコレクションとして格納できます。
例外オブジェクトの作成時にコンストラクターに渡されるエラー メッセージ文字列はローカライズする必要があり、クラスを使用 ResourceManager してリソース ファイルから指定できます。 ローカライズされたリソースの詳細については、「 サテライト アセンブリの作成 と リソースのパッケージ化とデプロイ」トピックを 参照してください。
例外が発生した理由に関する広範な情報をユーザーに提供するために、 HelpLink プロパティはヘルプ ファイルへの URL (または URN) を保持できます。
このクラスでは Exception 、値が0x80131500されている HRESULT COR_E_EXCEPTIONを使用します。
クラスのインスタンスの初期プロパティ値の Exception 一覧については、コンストラクターを Exception 参照してください。
パフォーマンスに関する考慮事項
例外をスローまたは処理すると、大量のシステム リソースと実行時間が消費されます。 例外をスローするのは、予測可能なイベントやフロー制御を処理するためではなく、本当に異常な条件を処理する場合のみです。 たとえば、クラス ライブラリを開発する場合など、メソッド引数が無効な場合は例外をスローするのが妥当な場合があります。これは、メソッドが有効なパラメーターを使用して呼び出されることを想定しているためです。 無効なメソッド引数が使用エラーの結果でない場合は、異常なことが発生したことを意味します。 逆に、ユーザー入力が無効な場合は例外をスローしないでください。これは、ユーザーが無効なデータを入力する場合があるためです。 代わりに、ユーザーが有効な入力を入力できるように再試行メカニズムを指定します。 また、使用エラーを処理するために例外を使用する必要もありません。 代わりに、 アサーションを 使用して、使用エラーを特定して修正します。
また、戻りコードで十分な場合は例外をスローしないでください。戻りコードを例外に変換しないでください。例外を定期的にキャッチし、無視してから処理を続行します。
例外を再スローする
多くの場合、例外ハンドラーは単に例外を呼び出し元に渡す必要があります。 これは、ほとんどの場合、次の場合に発生します。
クラス ライブラリは、.NET Framework クラス ライブラリまたはその他のクラス ライブラリ内のメソッドの呼び出しをラップします。
致命的な例外が発生したアプリケーションまたはライブラリ。 例外ハンドラーは、例外をログに記録してから、例外を再スローできます。
例外を再スローする推奨される方法は、C# で throw ステートメント、F# の reraise 関数、および式を含めずに、Visual Basicの Throw ステートメントを使用することです。 これにより、例外が呼び出し元に伝達されるときに、すべての呼び出し履歴情報が保持されます。 次の例を使って説明します。 文字列拡張メソッドは、 FindOccurrences
引数を事前に String.IndexOf(String, Int32) 検証せずに 1 つ以上の呼び出しをラップします。
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public static class Library
{
public static int[] FindOccurrences(this String s, String f)
{
var indexes = new List<int>();
int currentIndex = 0;
try {
while (currentIndex >= 0 && currentIndex < s.Length) {
currentIndex = s.IndexOf(f, currentIndex);
if (currentIndex >= 0) {
indexes.Add(currentIndex);
currentIndex++;
}
}
}
catch (ArgumentNullException e) {
// Perform some action here, such as logging this exception.
throw;
}
return indexes.ToArray();
}
}
open System
module Library =
let findOccurrences (s: string) (f: string) =
let indexes = ResizeArray()
let mutable currentIndex = 0
try
while currentIndex >= 0 && currentIndex < s.Length do
currentIndex <- s.IndexOf(f, currentIndex)
if currentIndex >= 0 then
indexes.Add currentIndex
currentIndex <- currentIndex + 1
with :? ArgumentNullException ->
// Perform some action here, such as logging this exception.
reraise ()
indexes.ToArray()
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Public Module Library
<Extension()>
Public Function FindOccurrences(s As String, f As String) As Integer()
Dim indexes As New List(Of Integer)
Dim currentIndex As Integer = 0
Try
Do While currentIndex >= 0 And currentIndex < s.Length
currentIndex = s.IndexOf(f, currentIndex)
If currentIndex >= 0 Then
indexes.Add(currentIndex)
currentIndex += 1
End If
Loop
Catch e As ArgumentNullException
' Perform some action here, such as logging this exception.
Throw
End Try
Return indexes.ToArray()
End Function
End Module
その後、呼び出し元は 2 回呼び出 FindOccurrences
します。 2 番目の呼び出しでは、呼び FindOccurrences
出し元は検索文字列として a null
を渡します。これにより、メソッドは String.IndexOf(String, Int32) 例外を ArgumentNullException スローします。 この例外はメソッドによって FindOccurrences
処理され、呼び出し元に返されます。 throw ステートメントは式なしで使用されるため、この例の出力は呼び出し履歴が保持されていることを示しています。
public class Example
{
public static void Main()
{
String s = "It was a cold day when...";
int[] indexes = s.FindOccurrences("a");
ShowOccurrences(s, "a", indexes);
Console.WriteLine();
String toFind = null;
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine("Message:\n {0}\n", e.Message);
Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace);
}
}
private static void ShowOccurrences(String s, String toFind, int[] indexes)
{
Console.Write("'{0}' occurs at the following character positions: ",
toFind);
for (int ctr = 0; ctr < indexes.Length; ctr++)
Console.Write("{0}{1}", indexes[ctr],
ctr == indexes.Length - 1 ? "" : ", ");
Console.WriteLine();
}
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message:
// Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
open Library
let showOccurrences toFind (indexes: int[]) =
printf $"'{toFind}' occurs at the following character positions: "
for i = 0 to indexes.Length - 1 do
printf $"""{indexes[i]}{if i = indexes.Length - 1 then "" else ", "}"""
printfn ""
let s = "It was a cold day when..."
let indexes = findOccurrences s "a"
showOccurrences "a" indexes
printfn ""
let toFind: string = null
try
let indexes = findOccurrences s toFind
showOccurrences toFind indexes
with :? ArgumentNullException as e ->
printfn $"An exception ({e.GetType().Name}) occurred."
printfn $"Message:\n {e.Message}\n"
printfn $"Stack Trace:\n {e.StackTrace}\n"
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message:
// Value cannot be null. (Parameter 'value')
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.findOccurrences(String s, String f)
// at <StartupCode$fs>.main@()
Module Example
Public Sub Main()
Dim s As String = "It was a cold day when..."
Dim indexes() As Integer = s.FindOccurrences("a")
ShowOccurrences(s, "a", indexes)
Console.WriteLine()
Dim toFind As String = Nothing
Try
indexes = s.FindOccurrences(toFind)
ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name)
Console.WriteLine("Message:{0} {1}{0}", vbCrLf, e.Message)
Console.WriteLine("Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace)
End Try
End Sub
Private Sub ShowOccurrences(s As String, toFind As String, indexes As Integer())
Console.Write("'{0}' occurs at the following character positions: ",
toFind)
For ctr As Integer = 0 To indexes.Length - 1
Console.Write("{0}{1}", indexes(ctr),
If(ctr = indexes.Length - 1, "", ", "))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' 'a' occurs at the following character positions: 4, 7, 15
'
' An exception (ArgumentNullException) occurred.
' Message:
' Value cannot be null.
' Parameter name: value
'
' Stack Trace:
' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
' ngComparison comparisonType)
' at Library.FindOccurrences(String s, String f)
' at Example.Main()
これに対し、例外が再スローされる場合は、〘を
throw e;
Throw e
raise e
ステートメントの場合、完全な呼び出し履歴は保持されず、この例では次の出力が生成されます。
'a' occurs at the following character positions: 4, 7, 15
An exception (ArgumentNullException) occurred.
Message:
Value cannot be null.
Parameter name: value
Stack Trace:
at Library.FindOccurrences(String s, String f)
at Example.Main()
もう少し面倒な方法は、新しい例外をスローし、元の例外の呼び出し履歴情報を内部例外に保持することです。 呼び出し元は、新しい例外のプロパティを使用して、スタック フレームと元の InnerException 例外に関するその他の情報を取得できます。 この場合、throw ステートメントは次のようになります。
throw new ArgumentNullException("You must supply a search string.",
e);
raise (ArgumentNullException("You must supply a search string.", e) )
Throw New ArgumentNullException("You must supply a search string.",
e)
次の例外ハンドラーが示すように、例外を処理するユーザー コードは、プロパティに元の例外に関する情報が含まれていること InnerException を認識する必要があります。
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine(" Message:\n{0}", e.Message);
Console.WriteLine(" Stack Trace:\n {0}", e.StackTrace);
Exception ie = e.InnerException;
if (ie != null) {
Console.WriteLine(" The Inner Exception:");
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name);
Console.WriteLine(" Message: {0}\n", ie.Message);
Console.WriteLine(" Stack Trace:\n {0}\n", ie.StackTrace);
}
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message: You must supply a search string.
//
// Stack Trace:
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
//
// The Inner Exception:
// Exception Name: ArgumentNullException
// Message: Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
try
let indexes = findOccurrences s toFind
showOccurrences toFind indexes
with :? ArgumentNullException as e ->
printfn $"An exception ({e.GetType().Name}) occurred."
printfn $" Message:\n{e.Message}"
printfn $" Stack Trace:\n {e.StackTrace}"
let ie = e.InnerException
if ie <> null then
printfn " The Inner Exception:"
printfn $" Exception Name: {ie.GetType().Name}"
printfn $" Message: {ie.Message}\n"
printfn $" Stack Trace:\n {ie.StackTrace}\n"
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
//
// An exception (ArgumentNullException) occurred.
// Message: You must supply a search string.
//
// Stack Trace:
// at Library.FindOccurrences(String s, String f)
// at Example.Main()
//
// The Inner Exception:
// Exception Name: ArgumentNullException
// Message: Value cannot be null.
// Parameter name: value
//
// Stack Trace:
// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
// ngComparison comparisonType)
// at Library.FindOccurrences(String s, String f)
Try
indexes = s.FindOccurrences(toFind)
ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name)
Console.WriteLine(" Message: {1}{0}", vbCrLf, e.Message)
Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace)
Dim ie As Exception = e.InnerException
If ie IsNot Nothing Then
Console.WriteLine(" The Inner Exception:")
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name)
Console.WriteLine(" Message: {1}{0}", vbCrLf, ie.Message)
Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, ie.StackTrace)
End If
End Try
' The example displays the following output:
' 'a' occurs at the following character positions: 4, 7, 15
'
' An exception (ArgumentNullException) occurred.
' Message: You must supply a search string.
'
' Stack Trace:
' at Library.FindOccurrences(String s, String f)
' at Example.Main()
'
' The Inner Exception:
' Exception Name: ArgumentNullException
' Message: Value cannot be null.
' Parameter name: value
'
' Stack Trace:
' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
' ngComparison comparisonType)
' at Library.FindOccurrences(String s, String f)
標準例外の選択
例外をスローする必要がある場合は、多くの場合、カスタム例外を実装する代わりに、.NET Frameworkで既存の例外の種類を使用できます。 次の 2 つの条件で標準の例外の種類を使用する必要があります。
使用エラー (つまり、メソッドを呼び出している開発者によって行われたプログラム ロジックのエラー) によって発生する例外をスローしています。 通常は、ArgumentExceptionArgumentNullException、 InvalidOperationExceptionNotSupportedException 例外オブジェクトをインスタンス化するときに例外オブジェクトのコンストラクターに指定する文字列は、開発者が修正できるようにエラーを記述する必要があります。 詳細については、Message プロパティを参照してください。
既存の.NET Framework例外を使用して呼び出し元に通知できるエラーを処理しています。 可能な限り最も派生した例外をスローする必要があります。 たとえば、メソッドで引数が列挙型の有効なメンバーである必要がある場合は、> ではなく (最も派生したクラス) をスロー InvalidEnumArgumentException する ArgumentException必要があります。
次の表に、一般的な例外の種類と、それらをスローする条件を示します。
例外 | 条件 |
---|---|
ArgumentException | メソッドに渡される null 以外の引数が無効です。 |
ArgumentNullException | メソッドに渡される引数は null . |
ArgumentOutOfRangeException | 引数が有効な値の範囲外です。 |
DirectoryNotFoundException | ディレクトリ パスの一部が無効です。 |
DivideByZeroException | 整数または Decimal 除算演算の分母は 0 です。 |
DriveNotFoundException | ドライブが使用できないか、存在しません。 |
FileNotFoundException | ファイルが存在しません。 |
FormatException | 値は、次のような Parse 変換メソッドによって文字列から変換される適切な形式ではありません。 |
IndexOutOfRangeException | インデックスは、配列またはコレクションの境界外にあります。 |
InvalidOperationException | メソッド呼び出しは、オブジェクトの現在の状態では無効です。 |
KeyNotFoundException | コレクション内のメンバーにアクセスするための指定されたキーが見つかりません。 |
NotImplementedException | メソッドまたは操作は実装されていません。 |
NotSupportedException | メソッドまたは操作はサポートされていません。 |
ObjectDisposedException | 破棄されたオブジェクトに対して操作が実行されます。 |
OverflowException | 算術演算、キャスト演算、または変換操作を実行すると、オーバーフローが発生します。 |
PathTooLongException | パスまたはファイル名がシステム定義の最大長を超えています。 |
PlatformNotSupportedException | この操作は、現在のプラットフォームではサポートされていません。 |
RankException | 次元数が正しくない配列がメソッドに渡されます。 |
TimeoutException | 操作に割り当てられた時間間隔の有効期限が切れています。 |
UriFormatException | 無効な Uniform Resource Identifier (URI) が使用されます。 |
カスタム例外の実装
次の場合、既存の.NET Framework例外を使用してエラー状態を処理することは十分ではありません。
例外に既存の.NET Framework例外にマップできない一意のプログラム エラーが反映されている場合。
例外で、既存の.NET Framework例外に適した処理とは異なる処理が必要な場合、または例外を同様の例外から明確に区別する必要がある場合。 たとえば、対象の整数型の範囲外の文字列の数値表現を解析するときに例外をスロー ArgumentOutOfRangeException する場合、呼び出し元がメソッドの呼び出し時に適切な制約付き値を指定しなかった結果のエラーに対して同じ例外を使用しないようにします。
このExceptionクラスは、.NET Framework内のすべての例外の基底クラスです。 多くの派生クラスは、クラスのメンバーの継承された動作に依存します。クラスのメンバー Exception をオーバーライドしたり、一意の Exceptionメンバーを定義したりすることはありません。
独自の例外クラスを定義するには:
を Exception継承するクラスを定義します。 必要に応じて、例外に関する追加情報を提供するためにクラスに必要な一意のメンバーを定義します。 たとえば、このクラスにはParamName、ArgumentException引数が例外の原因となったパラメーターの名前を指定するプロパティが含まれておりRegexMatchTimeoutException、このプロパティにはタイムアウト間隔をMatchTimeout示すプロパティが含まれています。
必要に応じて、変更または変更する機能を持つ継承されたメンバーをオーバーライドします。 ほとんどの既存の Exception 派生クラスは、継承されたメンバーの動作をオーバーライドしないことに注意してください。
カスタム例外オブジェクトがシリアル化可能かどうかを判断します。 シリアル化を使用すると、例外に関する情報を保存し、リモート処理コンテキストでサーバーとクライアント プロキシによって例外情報を共有できます。 例外オブジェクトをシリアル化できるようにするには、そのオブジェクトを属性で SerializableAttribute マークします。
例外クラスのコンストラクターを定義します。 通常、例外クラスには次のコンストラクターが 1 つ以上あります。
Exception()は、既定値を使用して新しい例外オブジェクトのプロパティを初期化します。
Exception(String)指定されたエラー メッセージを使用して新しい例外オブジェクトを初期化します。
Exception(String, Exception)指定されたエラー メッセージと内部例外を使用して新しい例外オブジェクトを初期化します。
Exception(SerializationInfo, StreamingContext)は、
protected
シリアル化されたデータから新しい例外オブジェクトを初期化するコンストラクターです。 例外オブジェクトをシリアル化可能にすることを選択した場合は、このコンストラクターを実装する必要があります。
次の例は、カスタム例外クラスの使用を示しています。 これは、 NotPrimeException
クライアントが素数ではない開始番号を指定して素数のシーケンスを取得しようとしたときにスローされる例外を定義します。 例外は、 NonPrime
例外の原因となった非素数を返す新しいプロパティを定義します。 このクラスは、保護されたパラメーターなしのコンストラクターと、シリアル化のためのパラメーターを持つSerializationInfoStreamingContextコンストラクターを実装するだけでなく、プロパティをNotPrimeException
サポートする 3 つの追加コンストラクターをNonPrime
定義します。 各コンストラクターは、素数以外の値を保持するだけでなく、基底クラスコンストラクターを呼び出します。 クラスも NotPrimeException
属性でマークされます SerializableAttribute 。
using System;
using System.Runtime.Serialization;
[Serializable()]
public class NotPrimeException : Exception
{
private int notAPrime;
protected NotPrimeException()
: base()
{ }
public NotPrimeException(int value) :
base(String.Format("{0} is not a prime number.", value))
{
notAPrime = value;
}
public NotPrimeException(int value, string message)
: base(message)
{
notAPrime = value;
}
public NotPrimeException(int value, string message, Exception innerException) :
base(message, innerException)
{
notAPrime = value;
}
protected NotPrimeException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{ }
public int NonPrime
{ get { return notAPrime; } }
}
namespace global
open System
open System.Runtime.Serialization
[<Serializable>]
type NotPrimeException =
inherit Exception
val notAPrime: int
member this.NonPrime =
this.notAPrime
new (value) =
{ inherit Exception($"%i{value} is not a prime number."); notAPrime = value }
new (value, message) =
{ inherit Exception(message); notAPrime = value }
new (value, message, innerException: Exception) =
{ inherit Exception(message, innerException); notAPrime = value }
// F# does not support protected members
new () =
{ inherit Exception(); notAPrime = 0 }
new (info: SerializationInfo, context: StreamingContext) =
{ inherit Exception(info, context); notAPrime = 0 }
Imports System.Runtime.Serialization
<Serializable()> _
Public Class NotPrimeException : Inherits Exception
Private notAPrime As Integer
Protected Sub New()
MyBase.New()
End Sub
Public Sub New(value As Integer)
MyBase.New(String.Format("{0} is not a prime number.", value))
notAPrime = value
End Sub
Public Sub New(value As Integer, message As String)
MyBase.New(message)
notAPrime = value
End Sub
Public Sub New(value As Integer, message As String, innerException As Exception)
MyBase.New(message, innerException)
notAPrime = value
End Sub
Protected Sub New(info As SerializationInfo,
context As StreamingContext)
MyBase.New(info, context)
End Sub
Public ReadOnly Property NonPrime As Integer
Get
Return notAPrime
End Get
End Property
End Class
次の例に示すクラスは PrimeNumberGenerator
、Eratosthenes のシーブを使用して、クラス コンストラクターの呼び出しでクライアントによって指定された 2 から制限までの素数のシーケンスを計算します。 このメソッドは GetPrimesFrom
、指定した下限以上のすべての素数を返しますが、その下限が素数でない場合は a NotPrimeException
をスローします。
using System;
using System.Collections.Generic;
[Serializable]
public class PrimeNumberGenerator
{
private const int START = 2;
private int maxUpperBound = 10000000;
private int upperBound;
private bool[] primeTable;
private List<int> primes = new List<int>();
public PrimeNumberGenerator(int upperBound)
{
if (upperBound > maxUpperBound)
{
string message = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound);
throw new ArgumentOutOfRangeException(message);
}
this.upperBound = upperBound;
// Create array and mark 0, 1 as not prime (True).
primeTable = new bool[upperBound + 1];
primeTable[0] = true;
primeTable[1] = true;
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound));
ctr++)
{
if (primeTable[ctr]) continue;
for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++)
if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true;
}
// Populate array with prime number information.
int index = START;
while (index != -1)
{
index = Array.FindIndex(primeTable, index, (flag) => !flag);
if (index >= 1)
{
primes.Add(index);
index++;
}
}
}
public int[] GetAllPrimes()
{
return primes.ToArray();
}
public int[] GetPrimesFrom(int prime)
{
int start = primes.FindIndex((value) => value == prime);
if (start < 0)
throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime));
else
return primes.FindAll((value) => value >= prime).ToArray();
}
}
namespace global
open System
[<Serializable>]
type PrimeNumberGenerator(upperBound) =
let start = 2
let maxUpperBound = 10000000
let primes = ResizeArray()
let primeTable =
upperBound + 1
|> Array.zeroCreate<bool>
do
if upperBound > maxUpperBound then
let message = $"{upperBound} exceeds the maximum upper bound of {maxUpperBound}."
raise (ArgumentOutOfRangeException message)
// Create array and mark 0, 1 as not prime (True).
primeTable[0] <- true
primeTable[1] <- true
// Use Sieve of Eratosthenes to determine prime numbers.
for i = start to float upperBound |> sqrt |> ceil |> int do
if not primeTable[i] then
for multiplier = i to upperBound / i do
if i * multiplier <= upperBound then
primeTable[i * multiplier] <- true
// Populate array with prime number information.
let mutable index = start
while index <> -1 do
index <- Array.FindIndex(primeTable, index, fun flag -> not flag)
if index >= 1 then
primes.Add index
index <- index + 1
member _.GetAllPrimes() =
primes.ToArray()
member _.GetPrimesFrom(prime) =
let start =
Seq.findIndex ((=) prime) primes
if start < 0 then
raise (NotPrimeException(prime, $"{prime} is not a prime number.") )
else
Seq.filter ((>=) prime) primes
|> Seq.toArray
Imports System.Collections.Generic
<Serializable()> Public Class PrimeNumberGenerator
Private Const START As Integer = 2
Private maxUpperBound As Integer = 10000000
Private upperBound As Integer
Private primeTable() As Boolean
Private primes As New List(Of Integer)
Public Sub New(upperBound As Integer)
If upperBound > maxUpperBound Then
Dim message As String = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound)
Throw New ArgumentOutOfRangeException(message)
End If
Me.upperBound = upperBound
' Create array and mark 0, 1 as not prime (True).
ReDim primeTable(upperBound)
primeTable(0) = True
primeTable(1) = True
' Use Sieve of Eratosthenes to determine prime numbers.
For ctr As Integer = START To CInt(Math.Ceiling(Math.Sqrt(upperBound)))
If primeTable(ctr) Then Continue For
For multiplier As Integer = ctr To CInt(upperBound \ ctr)
If ctr * multiplier <= upperBound Then primeTable(ctr * multiplier) = True
Next
Next
' Populate array with prime number information.
Dim index As Integer = START
Do While index <> -1
index = Array.FindIndex(primeTable, index, Function(flag)
Return Not flag
End Function)
If index >= 1 Then
primes.Add(index)
index += 1
End If
Loop
End Sub
Public Function GetAllPrimes() As Integer()
Return primes.ToArray()
End Function
Public Function GetPrimesFrom(prime As Integer) As Integer()
Dim start As Integer = primes.FindIndex(Function(value)
Return value = prime
End Function)
If start < 0 Then
Throw New NotPrimeException(prime, String.Format("{0} is not a prime number.", prime))
Else
Return primes.FindAll(Function(value)
Return value >= prime
End Function).ToArray()
End If
End Function
End Class
次の例では、非素数を GetPrimesFrom
持つメソッドを 2 回呼び出します。そのうちの 1 つは、アプリケーション ドメインの境界を越えて行われます。 どちらの場合も、例外がスローされ、クライアント コードで正常に処理されます。
using System;
using System.Reflection;
class Example
{
public static void Main()
{
int limit = 10000000;
PrimeNumberGenerator primes = new PrimeNumberGenerator(limit);
int start = 1000001;
try
{
int[] values = primes.GetPrimesFrom(start);
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit);
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
AppDomain domain = AppDomain.CreateDomain("Domain2");
PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap(
typeof(Example).Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
new object[] { 1000000 }, null, null);
try
{
start = 100;
Console.WriteLine(gen.GetPrimesFrom(start));
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
}
}
open System
open System.Reflection
let limit = 10000000
let primes = PrimeNumberGenerator limit
let start = 1000001
try
let values = primes.GetPrimesFrom start
printfn $"There are {values.Length} prime numbers from {start} to {limit}"
with :? NotPrimeException as e ->
printfn $"{e.NonPrime} is not prime"
printfn $"{e}"
printfn "--------"
let domain = AppDomain.CreateDomain "Domain2"
let gen =
domain.CreateInstanceAndUnwrap(
typeof<PrimeNumberGenerator>.Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
[| box 1000000 |], null, null)
:?> PrimeNumberGenerator
try
let start = 100
printfn $"{gen.GetPrimesFrom start}"
with :? NotPrimeException as e ->
printfn $"{e.NonPrime} is not prime"
printfn $"{e}"
printfn "--------"
Imports System.Reflection
Module Example
Sub Main()
Dim limit As Integer = 10000000
Dim primes As New PrimeNumberGenerator(limit)
Dim start As Integer = 1000001
Try
Dim values() As Integer = primes.GetPrimesFrom(start)
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit)
Catch e As NotPrimeException
Console.WriteLine("{0} is not prime", e.NonPrime)
Console.WriteLine(e)
Console.WriteLine("--------")
End Try
Dim domain As AppDomain = AppDomain.CreateDomain("Domain2")
Dim gen As PrimeNumberGenerator = domain.CreateInstanceAndUnwrap(
GetType(Example).Assembly.FullName,
"PrimeNumberGenerator", True,
BindingFlags.Default, Nothing,
{1000000}, Nothing, Nothing)
Try
start = 100
Console.WriteLine(gen.GetPrimesFrom(start))
Catch e As NotPrimeException
Console.WriteLine("{0} is not prime", e.NonPrime)
Console.WriteLine(e)
Console.WriteLine("--------")
End Try
End Sub
End Module
' The example displays the following output:
' 1000001 is not prime
' NotPrimeException: 1000001 is not a prime number.
' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
' at Example.Main()
' --------
' 100 is not prime
' NotPrimeException: 100 is not a prime number.
' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
' at Example.Main()
' --------
Windows ランタイムと.NET Framework 4.5.1
Windows 8用の .NET for Windows 8.x Microsoft Store アプリでは、通常、例外が.NET Framework以外のスタック フレームを介して伝達されると、一部の例外情報が失われます。 .NET Framework 4.5.1 および Windows 8.1 以降、共通言語ランタイムは、.NET Framework以外のスタック フレームで例外が変更されない限り、スローされた元Exceptionのオブジェクトを引き続き使用します。
コンストラクター
Exception() |
Exception クラスの新しいインスタンスを初期化します。 |
Exception(SerializationInfo, StreamingContext) |
シリアル化したデータを使用して、Exception クラスの新しいインスタンスを初期化します。 |
Exception(String) |
指定したエラー メッセージを使用して、Exception クラスの新しいインスタンスを初期化します。 |
Exception(String, Exception) |
指定したエラー メッセージおよびこの例外の原因となった内部例外への参照を使用して、Exception クラスの新しいインスタンスを初期化します。 |
プロパティ
Data |
例外に関する追加のユーザー定義情報を提供する、キーと値のペアのコレクションを取得します。 |
HelpLink |
この例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。 |
HResult |
特定の例外に割り当てられているコード化数値である HRESULT を取得または設定します。 |
InnerException |
現在の例外の原因となる Exception インスタンスを取得します。 |
Message |
現在の例外を説明するメッセージを取得します。 |
Source |
エラーの原因となるアプリケーションまたはオブジェクトの名前を取得または設定します。 |
StackTrace |
呼び出し履歴で直前のフレームの文字列形式を取得します。 |
TargetSite |
現在の例外がスローされたメソッドを取得します。 |
メソッド
Equals(Object) |
指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。 (継承元 Object) |
GetBaseException() |
派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の根本原因である Exception を返します。 |
GetHashCode() |
既定のハッシュ関数として機能します。 (継承元 Object) |
GetObjectData(SerializationInfo, StreamingContext) |
派生クラスでオーバーライドされた場合は、その例外に関する情報を使用して SerializationInfo を設定します。 |
GetType() |
現在のインスタンスのランタイム型を取得します。 |
GetType() |
現在のインスタンスの Type を取得します。 (継承元 Object) |
MemberwiseClone() |
現在の Object の簡易コピーを作成します。 (継承元 Object) |
ToString() |
現在の例外の文字列形式を作成して返します。 |
events
SerializeObjectState |
互換性のために残されています。
例外がシリアル化され、例外に関するシリアル化されたデータを含む例外状態オブジェクトが作成されたときに発生します。 |