LoginSignup
4
7

More than 5 years have passed since last update.

try-catchの中でIDisposableがusingステートメントで使われた時のDispose()のタイミング

Last updated at Posted at 2015-08-27

初めてIDisposableのクラスを作ってライブラリの作成をしていて、例外処理でふと気になったので調べてみた。
と言っても知識ある人たちにとっては多分常識・・・。

※namespaceとかは省略

main.cs
class Program {
    void Main() {
        try {
            // 処理A
            using(var lib = new Library()) {
                // 処理B
                throw new Exception(); // 例外発生
            }
        }
        catch (Exception ex) {
            // 処理C
        }
    }
}
library.cs
class Library : IDisposable {
    public Library() {
        // Library初期化
    }

    public void Dispose() {
        // Library破棄
    }
}

【結果】
処理A→Library初期化→処理B→throw new Exception()→Library破棄→処理C

つまり例外に対する処理に一旦libが必要な時は、usingステートメントの中でtry-catchをすればいいと。

main2.cs
class Program {
    void Main() {
        try {
            // 処理A
            using(var lib = new Library()) {
                try {
                    // 処理B1
                    throw new Exception(); //例外発生
                }
                catch (Exception ex) {
                    // 処理B2
                    throw; //外側でも処理したいときに書く。
                }
            }
        }
        catch (Exception ex) {
            // 処理C
        }
    }
}

【結果】
処理A→Library初期化→処理B1→throw new Exception()→処理B2→throw ex→Library破棄→処理C

自分で書いておきながらあれだけど後者みたいな書き方する必要ない気もする・・・外側のtry-catchを消して内側のcatchで処理Cやればいいじゃん・・・?(悟り)

4
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7