码迷,mamicode.com
首页 > 编程语言 > 详细

JavaException的使用

时间:2018-09-30 11:27:25      阅读:187      评论:0      收藏:0      [点我收藏+]

标签: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) {
      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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!