Set up the exception package, set up a bank class, the class has a variable double balance represents a deposit, the bank class construction method can increase the deposit, the bank class has the withdrawal method withdrawal (double damount), when the amount of withdrawals is greater than the deposit , throws the insufficientfundsexception, the withdrawal amount is negative, throws Nagativefundsexception, if the new bank (100), represents the deposit bank 100 yuan, when uses the method withdrawal (150), Withdrawal (-15) throws a custom exception.
Package exception; Public classBank {Private Doublebalance; PublicBank (Doublebalance) {super (); This. Balance =balance; } Public voidWithDrawal (DoubleDamount) throws Insufficientfundsexception,nagativefundsexception {if(damount>balance) { Throw Newinsufficientfundsexception (); } if(damount<0) { Throw Newnagativefundsexception (); } } Public Static voidMain (string[] args) {Bank T=NewBank ( -); Try{T.withdrawal ( the); }Catch(Exception e) {e.printstacktrace (); } Try{T.withdrawal (- -); }Catch(Exception e) {e.printstacktrace (); } } }
package exception; public class Nagativefundsexception extends Exception { public String GetMessage () { return Withdrawals cannot be negative ; }}
Package exception; Public class Insufficientfundsexception extends Exception { public String getMessage () { return " Insufficient Balance " ; }}
Java Exception Handling Exercise 2