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.
Packageexception; Public classBank {Doublebalance; PublicBank (Doublebalance) { } Public voidWithDrawal (DoubleDamount)throwsException {if(damount>balance) { Throw Newinsufficientfundsexception (); } if(damount<0) { Throw Newnagativefundsexception (); } Balance=balance-Damount; }}
Package exception; Public class extends Exception { @Override public String getMessage () { // TODO Auto-generated method stub return "Insufficient balance!" "; } }
Package exception; Public class extends Exception { @Override public String getMessage () { // TODO Automatically generated method stub return "The number of withdrawals cannot be negative";} }
Packageexception; Public classTest1 { Public Static voidMain (string[] args) {//TODO Auto-generated method stubsBank b=NewBank (100); Try{B.withdrawal (150); } Catch(Exception e) {System.out.println (E.getmessage ()); } Try{B.withdrawal (-15); } Catch(Exception e) {System.out.println (E.getmessage ()); } }}
Java Exception exercises 1