開発環境
- 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-2を解いてみる。
その他参考書籍
練習16-2.
コード
using System; class CustomCatError : Exception { public CustomCatError(string msg) : base(msg) { } } 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 CatManager(Cat cat) { if (cat.Age <= 0) { throw new CustomCatError("猫の年齢が0以下!"); } Console.WriteLine(cat.Age); } public void Run() { try { Cat tama = new Cat(5); Cat sora = new Cat(-5); Cat[] cats = { tama, sora }; foreach (Cat cat in cats) { CatManager(cat); } } catch (CustomCatError e) { Console.WriteLine(e.Message); } 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 猫の年齢が0以下! 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var Cat = function( age ) { var age = age; this.getAge = function( ) { return age; }; }; var tama = new Cat(5), sora = new Cat(-5), cats = [tama, sora], result = "", i; function catManager( cat ) { if (cat.getAge() <= 0) { throw { type: "カスタム例外", message: "猫の年齢が0以下!" }; } return cat.getAge(); } try{ for (i = 0, max = cats.length; i < max; i += 1) { result += catManager( cats[i] ) + "\n"; } } catch (e) { result += e.type + ": " + 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 class CustomCatError(Exception): pass def catManager( cat ): if cat.getAge() <= 0: raise CustomCatError("猫の年齢が0以下!") print(cat.getAge()) try: tama = Cat(5) sora = Cat(-5) cats = [tama, sora] for cat in cats: catManager(cat) except CustomCatError as err: print(err) import sys print(sys.exc_info()) except IndexError as err: print(err)
入出力結果(Terminal)
$ ./sample.py 5 猫の年齢が0以下! (<class '__main__.CustomCatError'>, CustomCatError('猫の年齢が0以下!',), <traceback object at 0x108035dd0>) $
0 コメント:
コメントを投稿