摘自《java 2 实用教程》 java自定义异常类

class BankException extends Exception {
	String message;

	public BankException(int m, int n) {
		message = "入账资金" + m + "是负数或者支出" + n + "是正数,不符合系统要求。";
	}

	public String warnMessage() {
		return message;
	}
}

class Bank {
	private int money;

	public void income(int in, int out) throws BankException {
		if (in <= 0 || out >= 0 || in + out <= 0) {
			throw new BankException(in, out);// 方法抛出异常,导致方法结束
		}
		int netIcome = in + out;
		System.out.println("本次计算出的纯收入是:" + netIcome + "元。");
		money = money + netIcome;
	}

	public int getMoney() {
		return money;
	};
}

public class Lmt02 {

	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.println("银行目前有" + bank.getMoney() + "元。");
			bank.income(200, 100);
			bank.income(999999, -99);
		} catch (BankException e) {
			System.out.println("计算收益的过程中出现如下问题:");
			System.out.println(e.warnMessage());
		}
		System.out.println("银行目前有" + bank.getMoney() + "元。");
	}

}

你可能感兴趣的:(Java学习笔记)