開発環境
- Microsoft Windows 7 Home Premium (OS)
- Microsoft Visual C# 2010 Express Edition (IDE)
- 言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第16章(例外)16.12(練習問題)練習6-2を解いてみる。
その他参考書籍
練習16-2.
コード
using System;
using System.Collections.Generic;
class Cat
{
int age;
public Cat(int age)
{
this.age = age;
}
public int Age
{
get { return age; }
set { age = value; }
}
}
class CustomCatError : Exception
{
public CustomCatError(string message)
: base(message)
{ }
}
class Tester
{
public void CatManager(Cat cat)
{
if (cat.Age <= 0)
{
throw new CustomCatError("猫の年齢が0以下");
}
Console.WriteLine("Age: {0}", cat.Age);
}
public void Run()
{
try
{
Console.WriteLine("Catオブジェクトの割り当て開始");
Cat tama = new Cat(5);
Cat sora = new Cat(-5);
List<Cat> cats = new List<Cat>();
cats.Add(tama);
cats.Add(sora);
foreach (Cat cat in cats)
{
CatManager(cat);
}
Console.WriteLine("Catオブジェクトの割り当て狩猟");
}
catch (CustomCatError e)
{
Console.WriteLine("CustomCatError");
Console.WriteLine(e.Message);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("ArgumentOutOfRangeException");
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine("未知の例外");
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Catオブジェクトの割り当ての解除");
}
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
入出力結果(Console Window)
Catオブジェクトの割り当て開始 Age: 5 CustomCatError 猫の年齢が0以下 Catオブジェクトの割り当ての解除 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿