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