我有以下ruby类:
class Money
attr_accessor :amount, currency
def initialize(amount, currency)
@amount = amount
@currency = currency
end
end
假设我创建了一个类的实例:
money = Money.new(0, 'BR')
很明显,我不能创建金额小于或等于0的钱。在这种情况下,我想为我的班级创建一个自定义例外。在纯ruby应用程序中执行此操作的最佳方法是什么?
答案 0 :(得分:2)
您也可以在Money
类中创建它,如下所示:
class Money
InvalidAmountError = Class.new(StandardError)
attr_accessor :amount, :currency
def initialize(amount, currency)
raise InvalidAmountError, "Amount must be greater than 0" if amount <= 0
@amount = amount
@currency = currency
end
end
测试它:
> Money.new(0, 'BR')
> Money::InvalidAmountError: Amount must be greater than 0
答案 1 :(得分:0)
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.12/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>
<button id="init">
INIT
</button>
<button id="move">
MOVE
</button>
结帐this blog了解更多详情