LoginSignup
2
2

More than 3 years have passed since last update.

C#のTry Catch Finally Throw

Last updated at Posted at 2019-12-20

タイトルの通り、C#での例外をCatch句内でthrowした挙動を確認してみました。

環境:Visual Studio2017,.net472

Form.cs
private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text += "①実行開始" + Environment.NewLine;
    try
    {
        Method();
    }
    catch
    {
        textBox1.Text += "⑤実行中 呼び出し元のCatch" + Environment.NewLine;
    }
    textBox1.Text += "⑥実行完了" + Environment.NewLine;
}

private void Method()
{
    try
    {
        textBox1.Text += "②実行中 Try" + Environment.NewLine;
        throw new Exception();
    }
    catch
    {
        textBox1.Text += "③実行中 Catch" + Environment.NewLine;
        throw;
    }
    finally
    {
        textBox1.Text += "④実行中 Finally" + Environment.NewLine;
    }
    textBox1.Text += "⑤実行されない Try外" + Environment.NewLine;
}

実行結果

①実行開始
②実行中 Try
③実行中 Catch
④実行中 Finally
⑤実行中 呼び出し元のCatch
⑥実行完了

知識の浅い自分は'throw'したらFinallyの実行順がどうなるのか…?
と思って確認した結果です。

2
2
0

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
2
2