開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第16章(例外)14.6(練習問題)練習16-2を解いてみる。
その他参考書籍
練習16-2.
コード
using System; using System.Collections.Generic; class Cat { private int age; public Cat(int age) { this.age = age; } public int Age { get { return age; } } } class CustomCatError : Exception { public CustomCatError(string msg) : base(msg) { } } class Tester { void CatManager(Cat cat) { if (cat.Age <= 0) { throw new CustomCatError("猫の年齢が0以下になっています!"); } Console.WriteLine("猫の年齢: {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("tryブロック終了"); } catch (CustomCatError e) { Console.WriteLine(e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("Catオブジェクトの割り当て解除"); } } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
Catオブジェクトの割り当て開始 猫の年齢: 5 猫の年齢が0以下になっています! Catオブジェクトの割り当て解除 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var Cat = function(age){ var age = age; this.get_age = function(){ return age; }; }; Cat.prototype.cat_manager = function(){ if(this.get_age() <= 0) throw "猫の年齢が0以下になっています!"; $('#pre0').append("猫の年齢: " + this.get_age() + "\n"); }; try{ $('#pre0').append("Catオブジェクトの割り当て開始\n"); var tama = new Cat(5); var sora = new Cat(-5); var cats = [tama, sora]; for(var i = 0; i < cats.length; i++){ cats[i].cat_manager(); } $('#pre0').append("tryブロックの終了\n"); } catch (e){ $('#pre0').append(e + "\n"); } finally { $('#pre0').append("Catオブジェクトの割り当て解除\n") }
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3 # -*- coding: utf-8 -*- class Cat: def __init__(self, age): self._age = age def get_age(self): return self._age class CustomError(Exception): def __init__(self, msg): self.msg = msg def __repr__(self): return self.msg def cat_manager(cat): if cat.get_age() <= 0: raise CustomError("猫の年齢が0以下になっています!") print(cat.get_age()) try: print("Catオブジェクトの割り当て開始") tama = Cat(5) sora = Cat(-5) cats = [tama, sora] for cat in cats: cat_manager(cat) print("tryブロックの終了") except CustomError as err: print(err) except IndexError as err: print(err) except Exception as err: print(err) finally: print("Catオブジェクトの割り当て解除")
入出力結果(Terminal)
$ ./sample.py Catオブジェクトの割り当て開始 5 猫の年齢が0以下になっています! Catオブジェクトの割り当て解除 $
0 コメント:
コメントを投稿