Reputation: 1
I am needing to have a basic error catching that produces an error statement if the user types in a negative interest rate. Currently I have this loan calculator that produces an error about the negative interest rate but it is in an if else statement. I do have a try catch statement as well, but it only produce an error message if the user types in something other than a number. Any direction/tips on how to have the try catch statement produce the error for my negative interest rate would be great. Thanks
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);
}
}
Upvotes: 0
Views: 305
Reputation: 31184
My advice would be to stick with the if
/else
statement.
Avoid using try
/catch
to catch preventable errors. That's not best practice.
If you're dead set on throwing an exception, then you can type
throw new ArgumentException("You have entered an invalid character");
You can technically throw any kind of exception, but ArguementException
is commonly used for when you have invalid parameters.
Bear in mind that if you catch this exception right away, then the entire purpose of the exception is lost
Upvotes: 1