如果用户键入负利率,我需要有一个基本错误捕获产生错误声明。目前我有这个贷款计算器产生关于负利率的错误,但它在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);
}
}
答案 0 :(得分:1)
我的建议是坚持使用if
/ else
声明。
避免使用try
/ catch
来捕获可预防的错误。这不是最佳做法。
如果你因为抛出异常而死定,那么你可以输入
throw new ArgumentException("You have entered an invalid character");
您可以在技术上抛出任何类型的异常,但ArguementException
通常用于有无效参数时。
请记住,如果您立即捕获此异常,则异常的整个目的都将丢失