WPF-例外処理
例外は、プログラムの実行中に発生したエラー状態または予期しない動作です。多くの理由で例外が発生する可能性がありますが、その一部は次のとおりです。
コードまたは呼び出すコード(共有ライブラリなど)の障害、
利用できないオペレーティングシステムリソース、
共通言語ランタイムが遭遇する予期しない条件(検証できないコードなど)
構文
例外には、プログラムのフローをある部分から別の部分に転送する機能があります。.NET Frameworkでは、例外処理には次の4つのキーワードがあります-
try −このブロックでは、プログラムはいくつかの例外を発生させる特定の条件を識別します。
catch− catchキーワードは、例外のキャッチを示します。Atry ブロックの後に1つ以上が続く catch 問題を処理したいプログラム内の場所で例外ハンドラーを使用して例外をキャッチするためのブロック。
finally−finallyブロックは、例外がスローされるかどうかに関係なく、特定のステートメントのセットを実行するために使用されます。たとえば、ファイルを開く場合、例外が発生するかどうかに関係なく、ファイルを閉じる必要があります。
throw−問題が発生すると、プログラムは例外をスローします。これは、throwキーワードを使用して行われます。
これらの4つのキーワードを使用する構文は次のとおりです。
try {
///This will still trigger the exception
}
catch (ExceptionClassName e) {
// error handling code
}
catch (ExceptionClassName e) {
// error handling code
}
catch (ExceptionClassName e) {
// error handling code
}
finally {
// statements to be executed
}
プログラムフローの状況に応じて、tryブロックが複数の例外を発生させる可能性がある場合は、複数のcatchステートメントが使用されます。
階層
.NET Frameworkのほとんどすべての例外クラスは、直接的または間接的にExceptionクラスから派生しています。Exceptionクラスから派生した最も重要な例外クラスは次のとおりです。
ApplicationException class−プログラムによって生成される例外をサポートします。開発者が例外を定義したい場合、クラスはこのクラスから派生する必要があります。
SystemException class−これは、事前定義されたすべてのランタイムシステム例外の基本クラスです。次の階層は、ランタイムによって提供される標準の例外を示しています。

次の表に、ランタイムによって提供される標準の例外と、派生クラスを作成する必要がある条件を示します。
例外タイプ | ベースタイプ | 説明 |
---|---|---|
Exception | オブジェクト | すべての例外の基本クラス。 |
SystemException | 例外 | ランタイムで生成されたすべてのエラーの基本クラス。 |
IndexOutOfRangeException | SystemException | 配列が不適切にインデックス付けされている場合にのみ、ランタイムによってスローされます。 |
NullReferenceException | SystemException | nullオブジェクトが参照されている場合にのみ、ランタイムによってスローされます。 |
AccessViolationException | SystemException | 無効なメモリにアクセスした場合にのみ、ランタイムによってスローされます。 |
InvalidOperationException | SystemException | 無効な状態のときにメソッドによってスローされます。 |
ArgumentException | SystemException | すべての引数例外の基本クラス。 |
ArgumentNullException | ArgumentException | 引数をnullにできないメソッドによってスローされます。 |
ArgumentOutOfRangeException | ArgumentException | 引数が指定された範囲内にあることを確認するメソッドによってスローされます。 |
ExternalException | SystemException | 発生する、またはランタイム外の環境を対象とする例外の基本クラス。 |
SEHException | ExternalException | Win32構造化例外処理情報をカプセル化する例外。 |
例
概念をよりよく理解するために、簡単な例を見てみましょう。名前で新しいWPFプロジェクトを作成することから始めますWPFExceptionHandling。
1つのテキストボックスをツールボックスからデザインウィンドウにドラッグします。次のXAMLコードは、テキストボックスを作成し、いくつかのプロパティで初期化します。
<Window x:Class = "WPFExceptionHandling.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFExceptionHandling"
mc:Ignorable = "d"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<TextBox x:Name = "textBox" HorizontalAlignment = "Left"
Height = "241" Margin = "70,39,0,0" TextWrapping = "Wrap"
VerticalAlignment = "Top" Width = "453"/>
</Grid>
</Window>
これは、C#での例外処理を使用したファイルの読み取りです。
using System;
using System.IO;
using System.Windows;
namespace WPFExceptionHandling {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
ReadFile(0);
}
void ReadFile(int index) {
string path = @"D:\Test.txt";
StreamReader file = new StreamReader(path);
char[] buffer = new char[80];
try {
file.ReadBlock(buffer, index, buffer.Length);
string str = new string(buffer);
str.Trim();
textBox.Text = str;
}
catch (Exception e) {
MessageBox.Show("Error reading from "+ path + "\nMessage = "+ e.Message);
}
finally {
if (file != null) {
file.Close();
}
}
}
}
}
上記のコードをコンパイルして実行すると、テキストボックス内にテキストが表示される次のウィンドウが生成されます。

例外が発生した場合、または手動でスローした場合(次のコードのように)、エラーのあるメッセージボックスが表示されます。
using System;
using System.IO;
using System.Windows;
namespace WPFExceptionHandling {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
ReadFile(0);
}
void ReadFile(int index) {
string path = @"D:\Test.txt";
StreamReader file = new StreamReader(path);
char[] buffer = new char[80];
try {
file.ReadBlock(buffer, index, buffer.Length);
string str = new string(buffer);
throw new Exception();
str.Trim();
textBox.Text = str;
}
catch (Exception e) {
MessageBox.Show("Error reading from "+ path + "\nMessage = "+ e.Message);
}
finally {
if (file != null) {
file.Close();
}
}
}
}
}
上記のコードの実行中に例外が発生すると、次のメッセージが表示されます。

上記のコードを実行して、その機能を試すことをお勧めします。