throw

throw で例外を投げて catch() で受け取ります。

前田稔(Maeda Minoru)の超初心者のプログラム入門

throw で例外を投げる

  1. 数字以外が検出されたとき、FormatException の例外を投げます。
    このプログラムは 例外とエラー処理 を参考にしました。
    //★ throw で例外を投げる
    using System;
    
    class console
    {
        // 1文字→整数
        static int CharToInt(char c)
        {
           if (c < '0' || '9' < c)
               throw new FormatException(); // 不正な文字のとき、例外を投げる
           return c - '0';
        }
    
        // 文字列→整数
        static int StringToInt(string str)
        {
           int val = 0;
           foreach(char c in str)
           {   int i = CharToInt(c);
               val = val * 10 + i;
           }
           return val;
        }
    
        static void Main()
        {   try
            {
                Console.Write("{0}\n", StringToInt("12345"));
                Console.Write("{0}\n", StringToInt("12a45"));
            }
            catch(FormatException)
            {   Console.Write("想定外の文字列が入力されました");  }
        }
    }
    
  2. CharToInt(char c) は一文字の数字を int に変換するメソッドです。
    ここで数字以外が検出されたとき FormatException() の例外を投げます。
           if (c < '0' || '9' < c)
               throw new FormatException(); // 不正な文字のとき、例外を投げる
        
  3. StringToInt(string str) は数字の文字列を int に変換するメソッドです。
    一文字ずつ取り出して、CharToInt(char c) で数値に変換します。
  4. Main() では try で StringToInt() を呼び出します。
    StringToInt("12345") は正常に変換されますが、StringToInt("12a45")で FormatException の例外が発生します。
    catch(FormatException) が呼び出されてエラーメッセージが表示されます。
        {   try
            {
                Console.Write("{0}\n", StringToInt("12345"));
                Console.Write("{0}\n", StringToInt("12a45"));
                //↑ ここで FormatException 例外が投げられる。
            }
            catch(FormatException)
            {   Console.Write("想定外の文字列が入力されました");  }
        }
        

独自の例外クラス

  1. 独自の例外クラスを定義して、発生させてみましょう。
    このプログラムは 独自の例外クラス を参考にしました。
    //★ 独自の例外クラス
    using System;
    
    class MyException : ApplicationException
    {
        public override string Message
        {
            get
            {   return "例外が発生しました";  }
        }
    }
    
    class console
    {
        public static void Main()
        {
            try
            {   throw new MyException();  }
            catch (MyException me)
            {   Console.WriteLine(me.Message);  }
    
            Console.WriteLine("try-catch を抜けました");
        }
    }
    
  2. class MyException が例外クラスの定義で、ApplicationException を継承します。
    string Message を override して、エラーメッセージをリターンします。
  3. Main() では try で throw new MyException() を実行します。
    class MyException が生成されて catch (MyException me) が呼び出されます。

MyException を組み込む

  1. プログラムに独自の例外クラス(MyException)を組み込みます。
    //★ 独自の例外クラスを組み込む
    using System;
    
    public class MyException : ApplicationException
    {
        public override string Message
        {
            get
            {   return "例外が発生しました";  }
        }
    }
    
    class console
    {
        public static int MyInput()
        {
            int no;
            Console.Write("整数値を入力--- ");
            string strNo = Console.ReadLine();
            try
            {   no = Int32.Parse(strNo);  }
            catch (Exception)
            {   throw new MyException();  }
            return no;
        }
    
        public static void Main()
        {   int no;
    
            try
            {   no = MyInput();  }
            catch(MyException me)
            {   Console.WriteLine(me.Message);
                no = -1;
            }
            Console.WriteLine(no);
        }
    }
    
  2. Main() の try から数値を入力する MyInput() メソッドを呼び出します。
    MyInput() メソッドで変換エラーが検出されると catch(MyException me) が呼び出されます。
  3. 数値を入力する MyInput() メソッドでは try と catch で入力文字列を no に変換します。
    変換に失敗すると throw new MyException() を実行します。
            {   no = Int32.Parse(strNo);  }
            catch (Exception)
            {   throw new MyException();  }
        
  4. プログラムを実行して、結果を確認して下さい。

超初心者のプログラム入門(C# Frame Work)