Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ チャレンジ:エラー処理 | データ構造とファイル操作
C#オブジェクト指向構造

bookチャレンジ:エラー処理

メニューを表示するにはスワイプしてください

try-catch 構文には、特定の種類のエラーを個別に捕捉して処理できる追加の構文があります。

index.cs

index.cs

copy
1234567891011121314151617
try { // code } catch (ExceptionType errorVarName) { // code } catch (ExceptionType errorVarName) { // code } ... finally { // code }

前の章で使用した Exception 型は、すべての種類のエラーを捕捉しますが、Exception にはより特定の種類のエラーを捕捉するサブタイプがいくつか存在します。以下は一般的な例外型です:

  1. DivideByZeroException: ゼロによる除算が発生した場合;
  2. FileNotFoundException: アクセスしようとしているファイルが存在しない場合;
  3. KeyNotFoundException: 辞書のキーが存在しない場合;
  4. IndexOutOfRangeException: 配列やリストの指定したインデックスが無効な場合。

errorVarName という用語は、Exception オブジェクトを格納する変数であり、errorVarName.Message でエラーメッセージなどの情報にアクセスできます。使用しない場合は省略可能です。

index.cs

index.cs

copy
12345678910111213
try { // code } catch (ExceptionType) { // code } ... finally { // code }

この種類の try-catch ブロックを使用する例を以下に示します。

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; class Program { static void Main(string[] args) { int[] myArray = { 0, 2, 4, 6, 8, 10 }; int i = 0; while (true) { try { Console.Write(myArray[i] / i + " "); i++; } catch(DivideByZeroException) { i++; } catch(IndexOutOfRangeException) { break; } } } }

これらの概念を使って、次のコードの空欄に適切な例外型を入力し、チャレンジを完成させてください。

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { int[] numbers = { 1, 2, 5, 7, 9 }; var numberNames = new Dictionary<int, string>(); numberNames.Add(1, "One"); numberNames.Add(2, "Two"); numberNames.Add(5, "Five"); numberNames.Add(9, "Nine"); int i = 0; while (true) { try { int key = numbers[i]; Console.WriteLine($"{key} is {numberNames[key]}"); i++; } catch (___) { break; } catch (___) { numberNames.Add(7, "Seven"); } } } }

catch ブロックに対して適切な例外型を使用してください。コードを読み、どの catch ブロックが特定の例外型を処理するのに最適かを理解しましょう。

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435
using System; using System.Collections.Generic; public class HelloWorld { public static void Main(string[] args) { int[] numbers = { 1, 2, 5, 7, 9 }; var numberNames = new Dictionary<int, string>(); numberNames.Add(1, "One"); numberNames.Add(2, "Two"); numberNames.Add(5, "Five"); numberNames.Add(9, "Nine"); int i = 0; while (true) { try { int key = numbers[i]; Console.WriteLine($"{key} is {numberNames[key]}"); i++; } catch (IndexOutOfRangeException) { break; } catch (KeyNotFoundException) { numberNames.Add(7, "Seven"); } } } }
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  10

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  10
some-alt