我无法获得下面的代码来执行异常!
我无法显示例外消息。 你能帮忙吗?最后有一个示例输出。
谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Account account = new Account();
try
{
double overdraftLimit = 1000;
double dailyWithdrawlLimit = 1000;
}
catch (OverdraftEx e1)
{
Console.WriteLine(e1.Message);
}
catch (DailyLimitEx e2)
{
Console.WriteLine(e2.Message);
}
account.display();
account.deposit(1500);
account.withdraw(1050);
account.withdraw(1000);
Console.WriteLine("-------------------");
account.withdraw(50);
account.endDay();
account.withdraw(50);
Console.ReadLine();
return;
}
}
class OverdraftEx : Exception
{
private static string msg = " Sorry, the amount you are trying to withdraw exceeds your allowed overdraft limit.";
public OverdraftEx() : base(msg)
{
}
}
class DailyLimitEx : Exception
{
private static string msg1 = " Sorry, you have exceeded your allowed daily withdrawal limit.";
public DailyLimitEx() : base(msg1)
{
}
}
class Account
{
public int accountID { get; set; }
public double amount;
public double balance;
public double Balance
{
get
{
return balance;
}
set
{
if (amount > overdraftLimit)
{
OverdraftEx ex1 = new OverdraftEx();
throw ex1;
}
}
}
public double overdraftLimit { get; set; }
public double dailyWithdrawlLimit
{
get
{
return dailyWithdrawlLimit;
}
set
{
if (amount > dailyWithdrawlLimit - 1000)
{
DailyLimitEx ex2 = new DailyLimitEx();
throw ex2;
}
}
}
public Account()
{
accountID = 10;
balance = 0;
return;
}
public Account(int accID, double accBalance)
{
accountID = accID;
balance = accBalance;
return;
}
public void withdraw(double amount)
{
Console.WriteLine("");
Console.WriteLine(" Attempting to withdraw $" + Math.Round(amount, 2));
balance = balance - amount;
Console.WriteLine(" Account #: " + accountID);
Console.WriteLine(" Your new balance is $" + Math.Round(balance, 2));
}
public void deposit(double amount)
{
// calculating the balance after depositing money
if (amount > 0)
{
Console.WriteLine(" Depositing $" + Math.Round(amount, 2));
balance = balance + amount;
Console.WriteLine(" Account #: " + accountID);
Console.WriteLine(" Balance: $" + Math.Round(balance, 2));
}
else
Console.WriteLine(" Sorry, amount is invalid");
Console.WriteLine("");
return;
}
public void display()
{
Console.WriteLine("");
Console.WriteLine(" Account ID: " + accountID);
Console.WriteLine(" Balance: $" + Math.Round(balance, 2));
Console.WriteLine("");
return;
}
public void endDay()
{
Console.WriteLine("");
Console.WriteLine(" End Day");
Console.WriteLine(" Account ID: " + accountID);
Console.WriteLine(" Balance: $" + Math.Round(balance, 2));
return;
}
}
}
样本输出: 注意:示例输出中的第一条错误消息应显示:“抱歉,您要提取的金额超过了您允许的透支额度”,而不是下面显示的内容。 Sample Output
答案 0 :(得分:0)
首先:您没有在方法withdraw()
和deposit()
中使用正确的名称。
它应该是Balance = Balance - amount
,而不是balance = balance - amount
。
第二:在Balance
的setter中,您不能使用给定值的新值。您可以通过关键字value
来引用新值,也不必更新属性的背景字段。