在编写程序时,可以扩展Exception类定义自己的异常类,然后根据程序的需要来规定哪些方法产生这样的异常。
一个方法在声明是可以使用throws关键字声明要产生的若干个异常,并在该方法中具体给出产生异常的操作,导致该方法结束执行。
程序必须在try catch块语句中调用能发生异常的方法,其中catch的作用就是捕获throw关键字抛出的异常对象。
银行存钱取钱有不同的正副值确定,则必须向参数in传递正数,参数out传递负数,并且in+out必须大于等于0.否则该方法就抛出异常。
示例:
class BankException extend Exception{
String message;
public BankException(int m,int n){
message = "入账资金"+m+"是负数或支出"+n+"是正数,不符合系统要求。";
}
public String warnMess(){
return message;
}
}
class Bank{
private int money;
public void income(int in,int out) throws Exception{
if(in <=0||out>=0||in+out<=0){
throw new BankException(in,out);//方法抛出异常,导致方法结束
}
int netIncome = in + out;
System.out.printf("本次计算出的纯收入是%d元\n",netIncome);
money = money + netIncome;
}
public int getMoney(){
return money;
}
}
public Example{
public static void main(String [] args){
Bank bank = new Bank();
try{
bank.income(200,-100);
bank.income(300,-100);
bank.income(400,-100);
System.out.printf("银行目前有%d\n",bank.getMoney());
bank.income(200,100);
bank.income(99999,-100);
}catch(BankException e){
System.out.println("计算收益过程中出现以下文艺");
System.out.println(e.warnMess());
}
System.out.println("银行目前有%d元\n",bank.getMoney());
}
}