Build the exception package, write the Testexception.java program, the main method has the following code, to determine the possible exceptions, to capture processing.
PackageCom.yichang; Public classTestException { Public Static voidMain (string[] args) { for(inti = 0; I < 4; i++) { intK; Switch(i) { Case0: Try{ intZero = 0; K= 911/Zero; Break;} Catch(Exception ex) {ex.printstacktrace (); System.out.println ("Running an arithmetic exception" +ex.getmessage ()); } Case1: Try{ intB[] =NULL; K= B[0];} Catch(Exception ex) {ex.printstacktrace (); System.out.println ("Run null pointer exception" +ex.getmessage ()); } Break; Case2: Try{ intC[] =New int[2]; K= C[9];} Catch(Exception ex) {ex.printstacktrace (); System.out.println ("Run Exception" +ex.getmessage ()); } Break; Case3: Try{ CharCH = "abc". CHARAT (99);} Catch(Exception ex) {ex.printstacktrace (); System.out.println ("Run Exception" +ex.getmessage ()); } Break; } } }}
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 class Insufficientfundsexception extends Exception { public Insufficientfundsexception ( String String {} public insuffic Ientfundsexception () {System.out.println ( "Insufficient balance" ); }}
Package exception; Public class extends Exception { public nagativefundsexception (String string) { } public nagativefundsexception () { System.out.println ("withdrawal cannot be negative");} }
Packageexception; Public classBank {Private Doublebalance; PublicBank (Doublebalance) { Super(); This. Balance =balance; } Public DoubleGetBalance () {returnbalance; } Public voidSetbalance (Doublebalance) { This. Balance =balance; } DoubleWithDrawal (DoubleDamount)throwsException {if(damount>balance) { Throw Newinsufficientfundsexception (); } if(damount<0) { Throw Newnagativefundsexception (); } return This. Balance; } Public Static voidMain (string[] args) {Bank b=NewBank (100); Try{B.withdrawal (150); } Catch(Exception e) {e.printstacktrace (); } Try{B.withdrawal (-15); } Catch(Exception e) {e.printstacktrace (); } }}
Java Exception Practice