本文へスキップ
BecomeCoder

C#文法コース · 第6章 例外処理とnull安全 · レッスン48

独自例外クラスと例外設計

ブラウザで完結

導入

「残高不足」「在庫切れ」のような業務固有のエラーは、Exception継承した独自例外クラスで表すと、呼び出し側が「どの種類のエラーか」で正確に対応できます。あわせて、条件を満たすときだけ捕まえるwhenフィルタも学びます。

図解

flowchart TB
    E["Exception(すべての例外の親)"] --> A["ArgumentException(標準)"]
    E --> C["InsufficientBalanceException<br/>(自作:業務エラー)"]
    C --> H["catch で種類ごとに対応できる"]
    style C fill:#fff3e0

サンプル

// 独自例外は Exception を継承して作る。メッセージは base(...) へ渡す
class InsufficientBalanceException : Exception
{
    public InsufficientBalanceException(string message) : base(message) { }
}

decimal balance = 1000m;
void Withdraw(decimal amount)
{
    if (amount > balance)
        throw new InsufficientBalanceException($"残高不足: 残高{balance}円, 請求{amount}円");
    balance -= amount;
}

try
{
    Withdraw(1500m);
}
catch (InsufficientBalanceException ex)
{
    Console.WriteLine(ex.Message);   // 残高不足: 残高1000円, 請求1500円
}

// when フィルタ: 条件を満たすときだけ catch する
try
{
    throw new ArgumentException("code=404");
}
catch (ArgumentException ex) when (ex.Message.Contains("404"))
{
    Console.WriteLine("404を専用処理");   // これが出力される
}
  • 独自例外はclass 名前 : Exceptionで作り、コンストラクタでbase(message)にメッセージを渡す
  • 業務エラーを型で表すと、catchで種類ごとに正確に対応できる
  • catch (型 ex) when (条件)で、条件を満たすときだけ捕まえられる(例外フィルタ

演習

int age = 15;
try
{
    if (age < 18) throw new TooYoungException("年齢制限です");
    Console.WriteLine("OK");
}
catch (TooYoungException ex)
{
    Console.WriteLine(ex.Message);
}

// TODO: Exception を継承した独自例外 TooYoungException を定義してください
___
  • 期待される出力: 年齢制限です
ヒント1を見る

class TooYoungException : Exception { public TooYoungException(string m) : base(m) { } }

ヒント2を見る

上のクラスをそのまま末尾に定義すれば、throw new TooYoungException(...)が使えます

まとめ

  • 業務固有のエラーはExceptionを継承した独自例外で表す
  • コンストラクタでbase(message)にメッセージを渡す
  • whenフィルタで「条件を満たすときだけcatch」できる

次回: nullによる事故を型で防ぐ「null許容参照型」です。

実際に動かしてみよう

本文のサンプルや演習のコードは、コードブロック右上の「コピー」ボタンでコピーして、下のエディタに貼り付ければそのまま実行できます。

C# — ブラウザ内で実行

ブラウザ内でC#を動かす環境を読み込みます(初回のみ数秒)。
スクロールして表示された時点でも自動で読み込まれます。