Ruby,创建自定义错误消息

时间:2014-10-05 21:36:21

标签: ruby-on-rails ruby custom-error-handling

这是代码,但其中很多都是无关紧要的:

class BankAccount

def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
    @balance = 0
end

def public_deposit(amount)
    @balance += amount
end

def protected_deposit(amount)
    @balance += amount
end
protected :protected_deposit

def private_deposit(amount)
    @balance += amount
end
private :private_deposit

def call_private_deposit(amount)
    private_deposit(amount)
end

def call_protected_deposit(amount)
    protected_deposit(amount)
end

#To show that you can't call a private method with a different instance of the same class.
def private_add_to_different_account(account, amount)
    account.private_deposit(amount)
end

#To show that you can call a protected method with a different instance of the same class.
def protected_add_to_different_account(account, amount)
    account.protected_deposit(amount)
end
end

我使用“load'./visibility.rb'”将此代码加载到irb中,然后创建一个实例:

an_instance = BankAccount.new("Joe", "Bloggs")

然后,我输入以下内容生成NoMethodError:

an_instance.protected_deposit(1000)

这将返回NoMethodError。这是故意的。但是,我想要发生的是返回自定义消息而不是标准的NoMethodError - 类似于“这是一个自定义错误消息。”

我已经在这里乱砍了几个小时而且我的智慧结束了。我是一个相对初学者,所以请记住这一点。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以解决错误:

def call_protected_method
  instance = BankAccount.new("Joe", "Bloggs")
  instance.protected_deposit(1000)
rescue NoMethodError
  puts "You called a protected method"
end

如果要返回自定义消息,可以解决错误并引发自己的自定义异常。 Ruby允许您定义自己的异常类。但我无法想象你为什么要这样做。你已经有一个内置的例外来处理这个问题。

相关问题