我正在制定一个简单的银行业务计划,我可以创建一个账户,并从账户存款和取款。
我遇到问题,我的代码在以下情况下显示错误消息:
退出资金不足的帐户时,应提示InsufficientFundsError
。当我做出否定撤回时,它应该提示NegativeAmountError
。
这是类文件:
class BankAccount
@@id = 0
def initialize( name )
@id = @@id = (@@id + 1)
@name = name
@balance = 0
end
def deposit( amount )
@balance += amount if amount > 0
end
def withdraw( amount )
@balance = @balance - amount
end
def to_s
"Account #@id - Balance: #@balance (#@name)"
end
end
class InsufficientFundsError < BankAccount
def initialize( id, balance, amount )
end
def to_s
"Account #{@id} has insufficient funds ($#{@balance}) to allow the withdrawal of $#{amount}"
end
end
class NegativeAmountError < BankAccount
def initialize( action, id )
end
def to_s
"You cannot [action] a negative amount for account [id]"
end
end
和驱动程序文件:
require_relative "bankaccount"
accounts = []
choice = 1
until choice == 5
puts "1. Open A Account Account"
puts "2. View you Accounts"
puts "3. Make A Deposit"
puts "4. Make A Withdrawal"
puts "5. Exit The Peoples Champ Bank"
print "What Business would you like to take care of today? Choose one: "
choice = gets.to_i
case choice
when 1 ;
if accounts.size < 6
print "What will the name of this account be? "
name = gets.chomp
accounts.push( BankAccount.new name )
puts "The Account has been created"
else
puts "You have exceeded the maximum number of accounts"
end
when 2 ;
accounts.each_with_index {|a, i| puts "#{i}. #{a}"}
when 3 ;
begin
print "What is the deposit amount? "
amount = gets.to_i
accounts.each_with_index {|a, i| puts "#{i}. #{a}"}
print "Which account would like to depositing to? "
accounts[ gets.to_i ].deposit( amount )
rescue NegativeAmountError => e
puts e.to_s
end
when 4 ;
begin
print "How much would you like to withdraw? "
amount = gets.to_i
accounts.each_with_index {|a, i| puts "#{i}. #{a}"}
print "Which account would you like to withdraw from? "
accounts[ gets.to_i ].withdraw( amount )
rescue InsufficientFundsError => e
puts e.to_s
end
end
end
答案 0 :(得分:0)
您似乎已正确使用begin
/ rescue
/ end
,但看起来您实际上并未检查错误情况并引发异常。
例如:
def withdraw(amount)
if @balance - amount < 0
raise InsufficientFundsError.new(@id, @balance, amount)
end
@balance = @balance - amount
end
此外,您的例外应该是Exception
的子类:
class InsufficientFundsError << Exception