From: Justin Gamble Date: 2012-11-16T06:33:21+09:00 Subject: Question on exceptions Hello! I have a simple bank program where I have to have an exception prompt on screen when someone tries to make a negative withdrawal and also when there are insufficient funds in the account to be withdrawn. This is what I have so far. Its in 2 separate files on my comp. One is the "driver" for the program whereas the other contains all the classes. DRIVER PROGRAM CODE $:.unshift File.dirname( __FILE__ ) require( "BankAccount" ) accounts = [] choice = -1 until choice == 5 puts "1. Open Account" puts "2. View Accounts" puts "3. Make Deposit" puts "4. Make Withdraw" puts "5. Exit" print "Choose: " choice = gets.to_i case choice when 1 ; if accounts.size < 6 print "Under what name? " name = gets.chomp accounts.push( BankAccount.new name ) puts "Account created" else puts "You already have the maximum number of accounts" end when 2 ; accounts.each_with_index {|a, i| puts "#{i}. #{a}"} when 3 ; begin print "How much to deposit? " amount = gets.to_i accounts.each_with_index {|a, i| puts "#{i}. #{a}"} print "Deposit to which account? " accounts[ gets.to_i ].deposit( amount ) rescue NegativeAmountError => e puts e end when 4 ; begin print "How much to withdraw? " amount = gets.to_i accounts.each_with_index {|a, i| puts "#{i}. #{a}"} print "Withdraw from which account? " accounts[ gets.to_i ].withdraw( amount ) rescue InsufficientFundsError => e puts e end end end CLASSES PROGRAM CODE 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 -= amount if amount > 0 and amount <= @balance end def to_s "Account #@id - Balance: #@balance (#@name)" end end class InsufficientFundsError 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 def initialize( action, id ) end def to_s "You cannot [action] a negative amount for account [id]" end end Like I said above, the two operations that I want this program to do are: 1) When making a withdrawal, it cant withdraw if there are insufficient funds thus prompting the InsufficientFundsError 2) You cant make a negative withdrawal thus prompting the NegativeAmountError Any words of wisdom would be greatly appreciated! -- Posted via http://www.ruby-forum.com/.