在异常中播放消息
本文关键字:消息 播放 异常 | 更新日期: 2023-09-27 18:35:14
我写了一些代码来测试银行账户,我完成了它(大部分)。目的是我尝试学习如何抛出和尝试/捕获异常。在大多数情况下,我学到了很多东西。我意识到这不是一个"例外"的情况,如果/否则陈述会更合适。我只是想学习异常处理。我正在尝试编写异常类来扩展类以包含一条新消息,详细说明在抛出异常时发送的错误。我阅读了什么是超类,或者 c# 中的基类,并尝试了一下。它编译并且看起来正确,但我不知道我做错了什么。有人可以向我解释为什么我的消息在抛出新的负存款异常中不会显示。
我希望它做的是抛出一条消息,而不是我在MessageBox.Show中放一个字符串。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public class NegativeBalanceException : Exception { }
public class NegativeWithdrawException : Exception { }
public class NegativeDepositException : Exception
{
public NegativeDepositException() { } // this doesn't do what I would like for it to do.
public NegativeDepositException(string message)
: base(message) { }
}
public Form1()
{
InitializeComponent();
}
public class BankAccount
{
decimal amount = 300.00m;
// Declare Delegate Type Object
public delegate void BankDelegate(decimal oldBalance, decimal newBalance);
// Create Delegate Type Events
public event BankDelegate OnDeposit;
public event BankDelegate OnWithdraw;
public void Deposit(decimal a)
{
if (a < 0)
throw new NegativeDepositException(); //"type some message here instead of messagebox below");
OnDeposit(this.amount, this.amount + a);
this.amount += a;
}
public void Withdraw(decimal a)
{
if (a < 0)
throw new NegativeWithdrawException();
OnWithdraw(this.amount, this.amount - a);
this.amount -= a;
if (this.amount < 0)
throw new NegativeBalanceException();
}
}
// this is my bank class variable...
BankAccount account = null;
private void Form1_Load(object sender, EventArgs e)
{
account = new BankAccount();
account.OnDeposit += new BankAccount.BankDelegate(account_OnDeposit);
account.OnWithdraw += new BankAccount.BankDelegate(account_OnWithdraw);
}
private void btnDeposit_Click(object sender, EventArgs e)
{
{
var amount = Convert.ToDecimal(textBox1.Text);
try { account.Deposit(amount); }
catch (NegativeDepositException)
{
MessageBox.Show("Cannot deposit negative amounts");
}
}
}
private void btnWIthdraw_Click(object sender, EventArgs e)
{
var amount = Convert.ToDecimal(textBox1.Text);
try { account.Withdraw(amount); }
catch (NegativeBalanceException)
{
MessageBox.Show("Cannot withdraw money that isn't there");
}
catch (NegativeWithdrawException)
{
MessageBox.Show("Cannot withdraw negative money");
}
}
void account_OnDeposit(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
void account_OnWithdraw(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
}
也许我误解了这个问题,但是您在抛出异常时没有传递消息;
它应该是:
if (a < 0)
throw new NegativeDepositException("Cannot deposit negative amounts");
捕获它时,您需要调用异常的 Message 属性(位于异常基类中)
catch (NegativeWithdrawException exception)
{
MessageBox.Show(exception.Message);
}