package exception;
/*
建立exception包,编写TestException.java程序,主方法中有以下代码,
确定其中可能出现的异常,进行捕获处理。
*/
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 e)
{
System.out.println(e.getMessage()+"\t被除数不能为零");
}
catch(NullPointerException e)
{
System.out.println(e.getMessage()+"\t空指针");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage()+"\t非法索引");
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e.getMessage()+"\t字符串索引越界");
}
}
}




package exception;
import javax.naming.InsufficientResourcesException;
public class CeshiBank
{
public static void main(String[] args) throws InsufficientResourcesException
{
Bank a = new Bank(100) ;
a.withDrawal(150);
a.withDrawal(-15);
}
}
class Bank
{
//成员属性
private double balance ;
//无参构造方法
public Bank()
{
}
//有参构造方法
public Bank(double balance)
{
this.balance = balance ;
}
//判断然后抛出异常
public void withDrawal(double dAmount) throws InsufficientResourcesException
{
if(dAmount < 0)
{
throw new NagativeFundsException("取款数为负") ;
}
if(dAmount > balance)
{
throw new InsufficientResourcesException("余额不足") ;
}
balance = balance - dAmount ;
}
}
//接收异常
class InsufficientFundsException extends RuntimeException
{
public InsufficientFundsException(String msg)
{
super(msg) ;
}
}
//接收异常
class NagativeFundsException extends RuntimeException
{
public NagativeFundsException(String msg)
{
super(msg) ;
}
}

