exceptiondemo.java~2~

来自「java2参考大全上的例子的源码和自己的理解.」· JAVA~2~ 代码 · 共 57 行

JAVA~2~
57
字号
package exceptiondemo;

/**
 例2 :在定义银行类时,若取钱数大于余额则作为异常处理(InsufficientFundsException).
 思路:产生异常的条件是余额少于取额, 因此是否抛出异常要判断条件
 取钱是withdrawal方法中定义的动作,因此在该方法中产生异常.
 处理异常安排在调用withdrawal的时候,因此withdrawal方法要声明异常,由上级方法调用
 要定义好自己的异常类
 */

class Bank {
  double balance;
  public void deposite(double dAmount) {
    if (dAmount > 0.0) {
      balance += dAmount;
    }
  }

  public void withdrawal(double dAmount) throws InsufficientFundsException {
    if (balance < dAmount) {
      throw new InsufficientFundsException(this, dAmount);
    }
    balance = balance - dAmount;
  }

  public void show_balance() {
    System.out.println("The balance is " + (int) balance);
  }
}

 class InsufficientFundsException extends Exception
{  private Bank  excepbank;
    private double excepAmount;

   InsufficientFundsException(Bank ba, double  dAmount)
   { excepbank=ba;
      excepAmount=dAmount;
   }
   public String  excepMesagge()
   {  String str="The balance"+ excepbank.show_balance();+
                         "The withdrawal was"+excepAmount;
       return str; }
}

public class ExceptionDemo {
   public static void main(String args[]) {
     try {
       Bank ba = new Bank(50);
       ba.withdrawal(100);
       System.out.println("Withdrawal successful!");
     }
     catch (Exception e) {
       System.out.println(e.toString());
     }
   }
 }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?