エラー処理
メニューを表示するにはスワイプしてください
前の章でランタイムエラーという用語に出会ったことがあるかもしれません。ランタイムエラーとは、プログラムの実行中に発生するエラーであり、そのため「ランタイム」エラーと呼ばれます。
通常、ランタイムエラーが発生すると、プログラムはクラッシュしたり応答しなくなったりします。
コンパイラはコード内のほとんどのエラーを指摘してくれますが、ランタイムエラーは多くの場合予測できず、不確定なパラメータに依存することが多いです。
例えば、StreamReaderに渡されたファイルパスが無効または存在しない場合、ランタイムエラーが発生し、プログラムがクラッシュします。そのため、このような危険なコードはtry-catchブロックに入れて、コードの実行を試み、失敗した場合にはエラーを捕捉して処理し、プログラムのクラッシュを防ぐことができます。
以下はtry-catchブロックの構文です。
index.cs
1234567try { // code to try } catch (Exception errorVar) { // code to handle error }
ここでExceptionは、データ型Exceptionを表すキーワードです。
例
index.cs
1234567891011121314151617using System; using System.IO; class Program { static void Main(string[] args) { try { new StreamWriter("C:/a/random/path/that/does/not/exist.txt"); } catch(Exception error) { Console.WriteLine(error.Message); } } }
(Exception error) を使用しない場合、catch 文から error 部分を省略できます。
以下は、実行時エラーが発生する一般的なケースです。
ゼロによる除算
index.cs
123456789101112131415161718using System; class Program { static void Main(string[] args) { try { int a = 100; int b = 0; int result = a / b; } catch { Console.WriteLine("ERROR: Division by Zero."); } } }
配列またはリストの無効なインデックス
index.cs
1234567891011121314151617using System; class Program { static void Main(string[] args) { try { var exampleArray = new int[10]; Console.WriteLine(exampleArray[20]); } catch { Console.WriteLine("ERROR: The array index is out of bounds."); } } }
キーが見つからない場合(ディクショナリ用):
index.cs
123456789101112131415161718192021using System; using System.Collections.Generic; class Program { static void Main(string[] args) { try { Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" } }; Console.WriteLine(myDict["key2"]); } catch { Console.WriteLine("Error: Key not found"); } } }
finally ブロック
finally ブロックは、catch ブロックの後に実行されるオプションのコードブロック。例外が発生したかどうかに関係なく、finally ブロックは常に try および catch ブロックの後に実行される。これにより、finally 内のコードが毎回実行されることが保証され、ファイルのクローズやリソースの解放などに有用となる。
index.cs
12345678910111213141516171819202122232425using System; using System.Collections.Generic; class Program { static void Main(string[] args) { try { Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" } }; Console.WriteLine(myDict["key2"]); } catch { Console.WriteLine("Error: Key not found"); } finally { Console.WriteLine("This line will show after the error"); } } }
1. 次のプログラムの出力は何ですか?
2. C#において、finallyブロックの目的は何ですか?
3. C# における try-catch ブロックについて、正しい記述はどれですか?
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください