c#中的基本错误捕获
本文关键字:错误 | 更新日期: 2023-09-27 18:15:35
我需要有一个基本的错误捕获,如果用户键入负利率,则产生错误语句。目前,我有这个贷款计算器,产生一个关于负利率的错误,但它是在一个if else语句。我也有一个try catch语句,但它只在用户输入数字以外的东西时产生错误消息。关于如何让try catch语句产生负利率错误的任何方向/提示将是伟大的。由于
namespace Program_3_Car_Calc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) // Calculate message box
{
double LoanAmount = 0;
double Payment = 0;
double InterestRate = 0;
double DownPayment = 0;
int PaymentPeriods = 0;
// Inputs
try
{
InterestRate = Convert.ToDouble(txtRate.Text);
PaymentPeriods = Convert.ToInt16(Convert.ToDouble(txtTime.Text) * 12);
LoanAmount = Convert.ToDouble(txtLoan.Text);
DownPayment = Convert.ToDouble(txtDown.Text);
// Calculate the monthly payment
if (InterestRate > 0)
{
InterestRate = InterestRate / 100;
}
else
{
MessageBox.Show("Error, Please enter a positive number");
}
Payment = ((LoanAmount - DownPayment) * Math.Pow((InterestRate / 12) + 1,
(PaymentPeriods)) * InterestRate / 12) / (Math.Pow(InterestRate / 12 + 1,
(PaymentPeriods)) - 1);
Payment = Math.Round(Payment, 2);
// Ouptput the results of the monthly payment
lblMonthlyPayment.Text = "Your Monthly Payment will be: " + "$" + Payment.ToString ("N2");
}
catch
{
MessageBox.Show("You have entered an invalid character");
}
}
private void CloseGoodbye(string message, string title = " ", int amount = 0) //Optional Parameter for amount of time message box appears
{
for (int i = 0; i < amount; i++)
MessageBox.Show(message, title);
Application.Exit();
}
private void cmdFinished_Click(object sender, EventArgs e) // Finished Message box
{
CloseGoodbye("Goodbye", "Loan Calc", 1);
}
}
我的建议是坚持使用if
/else
声明。
避免使用try
/catch
来捕获可预防的错误。这不是最佳实践。
如果你确定要抛出异常,那么你可以输入
throw new ArgumentException("You have entered an invalid character");
从技术上讲,您可以抛出任何类型的异常,但ArguementException
通常用于当您有无效参数时。
请记住,如果您立即捕获此异常,那么异常的整个目的就丢失了