前田稔(Maeda Minoru)の超初心者のプログラム入門
//★ 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("想定外の文字列が入力されました"); } } } |
if (c < '0' || '9' < c) throw new FormatException(); // 不正な文字のとき、例外を投げる |
{ try { Console.Write("{0}\n", StringToInt("12345")); Console.Write("{0}\n", StringToInt("12a45")); //↑ ここで FormatException 例外が投げられる。 } catch(FormatException) { Console.Write("想定外の文字列が入力されました"); } } |
//★ 独自の例外クラス 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 を抜けました"); } } |
//★ 独自の例外クラスを組み込む 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); } } |
{ no = Int32.Parse(strNo); } catch (Exception) { throw new MyException(); } |