開発環境
- OS: macOS High Sierra - Apple
- IDE(統合開発環境): Visual Studio for Mac
- プログラミング言語: C#
初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)、日向 俊二 (翻訳)、オライリージャパン)の16章(例外)、16.12(練習問題)、練習16-2.を取り組んでみる。
コード
using System;
using System.Collections.Generic;
namespace sample16_1
{
class CustomCatError : System.Exception
{
public CustomCatError(string message) : base(message) { }
}
class Cat
{
private int age;
public Cat(int age)
{
this.age = age;
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{
return string.Format("[Cat: Age={0}]", Age);
}
public void CatManager()
{
if (age <= 0)
{
throw new CustomCatError("年齢が0以下");
}
Console.WriteLine(this.ToString());
}
}
class Program
{
static void Main(string[] args)
{
Cat cat1 = new Cat(5);
Cat cat2 = new Cat(0);
Cat cat3 = new Cat(10);
List<Cat> cats = new List<Cat>() { cat1, cat2, cat3 };
try
{
foreach (var cat in cats)
{
try
{
cat.CatManager();
}
catch (CustomCatError ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Catオブジェクトの割り当てを解除");
}
}
}
}
入出力結果(Terminal)
[Cat: Age=5] 年齢が0以下 [Cat: Age=10] Catオブジェクトの割り当てを解除 Press any key to continue...
0 コメント:
コメントを投稿