Wpf-exception-handling
提供:Dev Guides
WPF-例外処理
例外は、プログラムの実行中に発生したエラー条件または予期しない動作です。 例外は多くの理由により発生する可能性があり、それらのいくつかは次のとおりです-
- コードまたは呼び出したコード(共有ライブラリなど)のエラー、
- 利用できないオペレーティングシステムリソース、
- 共通言語ランタイムが遭遇する予期しない条件(検証できないコードなど)
構文
例外には、プログラムのフローをある部分から別の部分に転送する機能があります。 .NETフレームワークでは、例外処理には次の4つのキーワードがあります-
- try -このブロックでは、プログラムは何らかの例外を発生させる特定の条件を識別します。
- catch -catchキーワードは、例外のキャッチを示します。 try ブロックの後に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ステートメントが使用されます。
階層
- * ApplicationExceptionクラス*-プログラムによって生成される例外をサポートします。 開発者が例外を定義する場合、クラスはこのクラスから派生する必要があります。
- * SystemExceptionクラス*-定義済みのすべてのランタイムシステム例外の基本クラスです。 次の階層は、ランタイムによって提供される標準の例外を示しています。
次の表に、ランタイムによって提供される標準の例外と、派生クラスを作成する必要がある条件を示します。
Exception type | Base type | Description |
---|---|---|
Exception | Object | Base class for all exceptions. |
SystemException | Exception | Base class for all runtime-generated errors. |
IndexOutOfRangeException | SystemException | Thrown by the runtime only when an array is indexed improperly. |
NullReferenceException | SystemException | Thrown by the runtime only when a null object is referenced. |
AccessViolationException | SystemException | Thrown by the runtime only when invalid memory is accessed. |
InvalidOperationException | SystemException | Thrown by methods when in an invalid state. |
ArgumentException | SystemException | Base class for all argument exceptions. |
ArgumentNullException | ArgumentException | Thrown by methods that do not allow an argument to be null. |
ArgumentOutOfRangeException | ArgumentException | Thrown by methods that verify that arguments are in a given range. |
ExternalException | SystemException | Base class for exceptions that occur or are targeted at environments outside the runtime. |
*SEHException * | ExternalException | Exception encapsulating Win32 structured exception handling information. |
例
概念をよりよく理解するために簡単な例を見てみましょう。* WPFExceptionHandling *という名前の新しいWPFプロジェクトを作成することから始めます。
ツールボックスからデザインウィンドウに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();
}
}
}
}
}
上記のコードの実行中に例外が発生すると、次のメッセージが表示されます。
上記のコードを実行し、その機能を実験することをお勧めします。