開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487312-194-7)の 第15章(例外)15.6(練習問題)練習16-1を解いてみる。
その他参考書籍
練習16-1.
コード
using System; class Cat { private int age; public Cat(int age) { this.age = age; } public int Age { get { return age; } set { age = value; } } } class Tester { public void Run() { try { Cat tama = new Cat(5); Cat sora = new Cat(10); Cat[] cats = { tama, sora }; for (int i = 0; i < 5; i++) { Console.WriteLine(cats[i].Age); } } catch (IndexOutOfRangeException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
5 10 インデックスが配列の境界外です。 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var Cat = function( age ) { var age = age; this.getAge = function( ) { return age; }; }; var tama = new Cat(5), sora = new Cat(10), cats = [tama, sora], result = "", i; try{ for (i = 0, max = 10; i < max; i += 1) { if ( i > cats.length - 1 ){ throw { type: "配列の長さ以上のインデックス", message: "エラー" }; } result += cats[i].getAge() + "\n"; } } catch (e) { result += e.type + "\n" + e.message; } $('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3 # -*- coding: utf-8 -*- class Cat: def __init__(self, age): self._age = age def getAge(self): return self._age try: tama = Cat(5) sora = Cat(10) cats = [tama, sora] for i in range(10): print(cats[i].getAge()) except IndexError as err: print(err)
入出力結果(Terminal)
$ ./sample.py 5 10 list index out of range $
0 コメント:
コメントを投稿