LoginSignup
0
2

More than 3 years have passed since last update.

[C#]例外処理を理解しよう

Last updated at Posted at 2020-02-26

1. 例外処理とは?

・ざっくり言うと想定内のエラーが発生した際にやる処理の事

2. 例外処理のメリット

・実行時に発生する問題に対応
・プログラムを安定して動作させる
・エラーメッセージを読み取れる

3. 例外処理(Exception)の機能

コマンド名 内容
・try あらかじめコードを指定して、プログラム実行時に処理の問題を検出
・catch 問題を検出した時、どのように対応するか記述しておく
・throw プログラム実行中に、例外が発生した事を知らせる

4. 例外が発生する例

・ゼロで割り算
・数値変換で、数字でない文字を指定
・配列の範囲外にアクセス
・ファイルが存在しない

5. 実例

・簡単な例外処理をしてみよう

Lesson1.cs
// 簡単な例外処理をしてみよう
using System;

class Lesson1
{
    public static void Main()
    {
        // 例外が投げられる可能性のあるコード
        try
        {
            Console.WriteLine("Hello World");

            int number = 0;
            // 0で割り算できないためエラーが起きる
            // ここで処理が中断され、catchブロックに飛ぶ
            int answer = 100 / number;
            Console.WriteLine(answer);
        }
        // 例外が起きた場合の処理
        // Exception e の中に例外の詳細情報が格納されている
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
        // 例外発生の有無にかかわらず実行したいコード
        finally
        {
            Console.WriteLine("Hello C#");
        }
    }
}

・throwで意図的に例外を投げよう

Lesson2.cs

// throwで意図的に例外を投げよう
using System;

class Lesson2
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        try
        {
            int number = 2;
            int answer = 100 / number;
            Console.WriteLine(answer);
            // 意図的に例外を投げる
            throw new Exception();
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("0では割り算できません");
            Console.Error.WriteLine(e);
        }
        // throw で呼ばれる
        catch (Exception e)
        {
            Console.WriteLine("例外が発生しました。");
            Console.Error.WriteLine(e);
        }
        finally
        {
            Console.WriteLine("Hello C#");
        }
    }
}
0
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
0
2