1.建立exception包,编写TestException.java程序,主方法中有以下代码,确定其中可能出现的异常,进行捕获处理。
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;
}
}
package exception; public class TestException { public static void main(String[] args) { try { for(int i=0;i<4;i++) { int k; switch(i) { // case 0: // int zero=0; // k=911/zero; // break; // case 1: // int b[]=null; // k = b[0]; // break; // case 2: // int c[]=new int[2]; // // k=c[9]; // break; case 3: char ch="abc".charAt(99); break; } } } // catch(ArithmeticException a) // { // System.out.println(a.getMessage()+"被除数不能为0"); // } // catch(NullPointerException n) // { // System.out.println(n.getMessage()+"空指针"); // n.printStackTrace(); // } // catch(ArrayIndexOutOfBoundsException ar) // { // System.out.println(ar.getMessage()+"索引超出长度"); // ar.printStackTrace(); // } catch(StringIndexOutOfBoundsException s) { System.out.println(s.getMessage()+"此处不能是字符串"); s.printStackTrace(); } } }
2.建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),表示存入银行100元,当用方法withdrawal(150),withdrawal(-15)时会抛出自定义异常。
package exception; public class Bank { double balance;//存款 public Bank(double balance) { super(); this.balance = balance; } //取款 //判断然后抛出异常 public void withDrawal(double dAmount) throws InsufficientResourcesException, NagativeFundsException { if(dAmount < 0) { throw new NagativeFundsException("取款数是负的") ; } if(dAmount > balance) { throw new InsufficientResourcesException("余额不足") ; } balance -= dAmount ; } }
package exception; public class InsufficientResourcesException extends Exception { //接受Bank抛出的异常 public InsufficientResourcesException(String msg) { super(msg) ; } }
package exception; public class NagativeFundsException extends Exception { public NagativeFundsException(String msg) { super(msg) ; } }
package exception; public class Ceshi_bank { public static void main(String[] args) throws InsufficientResourcesException, NagativeFundsException { // TODO 自动生成的方法存根 Bank b=new Bank(100); b.withDrawal(150); b.withDrawal(-15); } }