JavaException的使用

2021-06-16 03:03

阅读:586

标签:ack   模拟   main   pac   print   ati   一个   ber   this   

(第一个文件 MyException.java)

package exception;
import java.io.*;

//先创建自己的异常类继承与Exception的类

public class MyException extends Exception{
private double amount;
  public MyException(double amount) {
    this.amount = amount;
  }

  public double getAmount() {
    return amount;
  }
}

 

(第二个文件CheckingAccount .java)

package exception;

//模拟银行存取钱系统

public class CheckingAccount {
  private double blance;
  private int number;

  public CheckingAccount(int number) {
    this.number = number;
  }

  public void deposit(double amount) {
    blance += amount;
  }

  public void withdraw(double amount) throws MyException{
    if(amount       blance -= amount;
    }else {
      double needs = amount - blance;
      throw new MyException(needs);

    }
  }

  public double getBlance() {
    return blance;
  }

  public int getNumber() {
    return number;
  }
}

 

(第三个文件BankDemo.java)

package exception;

public class BankDemo {

//实例的应用

  public static void main(String[] args) {
    CheckingAccount c1 = new CheckingAccount(101);
    System.out.println("存500元。");
    c1.deposit(500);
    System.out.println("取200元。");
    try {
      c1.withdraw(200);
      double amount = c1.getBlance();
      System.out.println("账户余额:"+amount);

      System.out.println("取600元。");
      c1.withdraw(600);
    } catch (MyException e) {
      System.out.println("您的余额不足:差"+e.getAmount());
    }

  }
}

JavaException的使用

标签:ack   模拟   main   pac   print   ati   一个   ber   this   

原文地址:https://www.cnblogs.com/ZhuDianHui/p/9728565.html


评论


亲,登录后才可以留言!