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.
PackageYichang; Public classText { Public Static voidMain (string[] args) { for(inti=0;i<4;i++){ intK; Switch(i) { Case0: Try{ intZero=0; K=911/Zero; } Catch(ArithmeticException e) {System.out.println ("Incorrect input"); } Break; Case1: Try{ intb[]=NULL; K= B[0]; }Catch(NullPointerException e) {System.out.println ("Null pointer exception"); } Break; Case2: Try{ intc[]=New int[2]; K=c[9]; }Catch(arrayindexoutofboundsexception e) {System.out.println ("Index exceeded exception"); } Break; Case3: Try{ CharCh= "abc". CHARAT (99); }Catch(Exception e) {e.printstacktrace (); System.out.println ("Charge character exceeded"); } Break; } } }}
Results:
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 withdrawal method withdrawal (double damount), When the amount of withdrawal is greater than the deposit, throw insufficientfundsexception, the withdrawal amount is negative, throw nagativefundsexception, such as New Bank (100), said deposit bank 100 Yuan, When using the method withdrawal, withdrawal (-15) throws out the definition exception.
Package Yichang; Public class extends Exception { public String getMessage () { return "Insufficient balance" ; }}
Package Yichang; Public class extends public String getMessage () { return "withdrawal cannot be negative";}}
PackageYichang; Public classTest01 {Private Doublebalance; PublicTEST01 (Doublebalance) { Super(); This. Balance =balance; } Public voidWithDrawal (DoubleDamount)throwsinsufficientfundsexception,nagativefundsexception {if(damount>balance) { Throw Newinsufficientfundsexception (); } if(damount<0) { Throw Newnagativefundsexception (); } } Public Static voidMain (string[] args) {Test01 T=NewTEST01 (100); Try{T.withdrawal (150); }Catch(Exception e) {e.printstacktrace (); } Try{T.withdrawal (-10); }Catch(Exception e) {e.printstacktrace (); } }}
Results:
Java-Exception Handling Exercises