1. Create an exception package and write a TestException.java program. The main method contains the following code to determine possible exceptions and perform capture processing.
public class YiChang {public static void main(String[] args){for(int i=0;i<4;i++){int k;switch(i){case 0: int zero=0; try{k=911/zero;}catch(ArithmeticException e){System.out.println("ArithmeticException exception occurred!");}break;case 1: try{int b[]=null;k = b[0];}catch(NullPointerException e){System.out.println("Nullpointer exception occurred!");}break;case 2:int c[]=new int[2];try{k=c[9];}catch(ArrayIndexOutOfBoundsException e){System.out.println("Array number overflow occurs!");}break;case 3:try{char ch="abc".charAt(99);}catch(StringIndexOutOfBoundsException e){System.out.println("Data type conversion exception occurs!");}break;}}}}}} 2. Create an exception package and create a Bank class. There is a variable double balance in the class to represent deposits. The construction method of the Bank class can increase deposits. There is a withdrawal method withDrawal(double dAmount) in the Bank class. When the amount of withdrawal is greater than the deposit, an InsufficientFundsException is thrown. The withdrawal amount is negative. A NagativeFundsException is thrown. For example, new Bank(100), which means depositing 100 yuan in the bank. When using the method withdrawal(150) and withdrawal(-15), a custom exception will be thrown.
public class InsufficientFundsException extends Exception {public String getMessage(){return "Your balance is insufficient!";}} public class NagativeFundsException extends Exception{public String getMessage(){return "The withdrawal amount cannot be negative!";}} public class Bank {private static double balance;Bank(){};Bank(double balance){this.balance=balance;}public static void withDrawal(double dAmount) throws InsufficientFundsException,NagativeFundsException{if(dAmount>balance){throw new InsufficientFundsException();}if(dAmount<0){throw new NagativeFundsException();}}public static void main(String[] args){Bank b=new Bank(100);System.out.println("I have"+balance+"yuan deposit!");try{withDrawal(150);}catch(InsufficientFundsException | NagativeFundsException e){e.printStackTrace();}try{withDrawal(-15);}catch(NagativeFundsException |InsufficientFundsException e){e.printStackTrace();}} }I will introduce so many questions about Java exception handling to you. I hope it will be helpful to you. If you have any questions, please leave me a message. The editor will reply you in time. Thank you very much for your support to Wulin.com website!