2 changed files with 43 additions and 0 deletions
@ -0,0 +1,31 @@ |
|||
public class Account { |
|||
private double balance; |
|||
|
|||
public Account(double balance) { |
|||
this.balance = balance; |
|||
} |
|||
|
|||
public void withdraw(double amount) throws InsufficientFundsException { |
|||
if (amount > balance) { |
|||
throw new InsufficientFundsException(balance); |
|||
} |
|||
balance -= amount; |
|||
System.out.println("取款成功,当前余额: " + balance); |
|||
} |
|||
|
|||
public static void main(String[] args) { |
|||
Account account = new Account(1000.0); |
|||
|
|||
try { |
|||
account.withdraw(1500.0); |
|||
} catch (InsufficientFundsException e) { |
|||
System.out.println("取款失败: " + e.getMessage() + ",当前余额: " + e.getBalance()); |
|||
} |
|||
|
|||
try { |
|||
account.withdraw(500.0); |
|||
} catch (InsufficientFundsException e) { |
|||
System.out.println("取款失败: " + e.getMessage() + ",当前余额: " + e.getBalance()); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,12 @@ |
|||
public class InsufficientFundsException extends Exception { |
|||
private double balance; |
|||
|
|||
public InsufficientFundsException(double balance) { |
|||
super("余额不足"); |
|||
this.balance = balance; |
|||
} |
|||
|
|||
public double getBalance() { |
|||
return balance; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue