1. Build The exception package, write the Testexception.java program, the main method has the following code, to determine the possible exceptions, to capture processing.
for (inti=0;i<4;i++) {
int k;
switch (i) {
Case 0:
int zero=0;
K=911/zero;
Break
CASE1:
int b[]=null;
k = b[0];
Break
CASE2:
int c[]=new int[2];
K=C[9];
Break
CASE3:
Char ch= "abc". CHARAT (99);
Break
}
}
Public classTestException { Public Static voidMain (string[] args) {//TODO Auto-generated method stubs for(inti=0;i<4;i++){ intK; Switch(i) { Case0: intZero=0; Try{k=911/Zero;} Catch(Exception e) {System.out.println ("Caught exception" +e.getmessage ()); } Break; Case1: intb[]=NULL; Try{k= B[0]; } Catch(Exception e) {System.out.println ("Caught exception" +e.getstacktrace ()); } Break; Case2: intc[]=New int[2]; Try{k=c[9]; } Catch(Exception e) {System.out.println ("Caught the exception, I can still run!" "); } Break; Case3: Try{ CharCh= "abc". CHARAT (99); } Catch(Exception e) {System.out.println ("Finally, I'm going to have a rest time."); } Break; } } }}
2. Set up the exception package, set up the bank class, the class has variable double Balance represents the deposit, the Bank class construction method can increase the deposit, The Bank class has the method of withdrawing money withdrawal (double damount), when the amount of withdrawal is greater than the deposit, throws the insufficientfundsexception, the withdrawal amount is negative, Throwing nagativefundsexception, such as New Bank (100), means depositing 100 yuan into the bank, and when using the method withdrawal (withdrawal), the definition exception is thrown.
// Insufficientfundsexception J Inherit exception exception root parent class Public class extends Exception { insufficientfundsexception (String a) { }}
// Nagativefundsexception Inheriting exception exception root parent class Public class extends Exception { nagativefundsexception (String N) { }}
Public classBank {Private Doublebalance; Public DoubleGetBalance () {returnbalance; } Public voidSetbalance (Doublebalance) { This. Balance =balance; } PublicBank (DoubleMoney ) {Balance+=Money ; } //declaring an exception thrown Public voidWithDrawal (DoubleDamount)throwsinsufficientfundsexception,nagativefundsexception {if(Damount >balance) { //throw a custom exception Throw NewInsufficientfundsexception ("Insufficient withdrawal balance"); } //throw a custom exception Else if(Damount <0) { Throw NewNagativefundsexception ("The withdrawal balance is negative.")); } }}
Public Static void throws insufficientfundsexception, nagativefundsexception { // TODO Auto-generated method stub New Bank (100.0); B.withdrawal (); B.withdrawal (-15);} }
Java Base exception capture processing