Moose Moose - 4 days ago 5
Java Question

Throw exceptions in Java

I'm working on a mortgage calculator in Java. I have to validate the data using try and catch blocks. I have done the rest of the program, but I can't figure out how to implement the try and catch blocks. Here's what the prompt is asking for:

"Write your own exceptions to validate your data by using try and catch blocks. For example loan amount cannot be a negative number and it should be between $5000 and $1,000,000."

Edit: Here's the try-catch block that finally worked. It needed to be placed in the actionPerformed method where the rest of my data is. I had another issue where the code kept throwing an exception for any amount that I entered until I figured out that I needed to place the for loop inside of the try block.

try
{
if((n1 < 5000) || (n1 > 1000000))
throw new Exception();

for (int i = 0; i < term[0] * 12; i++)
{
double interest_paid = n1 * (rate[0] / 12);
double principal_paid = tr1 - interest_paid;
n1 = n1 - principal_paid;

//Prints the results.
edit.append("\n " + (i+1) + " \t\t " + (two.format(interest_paid))
+ " \t\t " + (two.format(principal_paid)) + " \t\t "
+ (two.format(Math.abs(n1))));
}
}
catch (Exception e)
{
edit.setText("Please enter an amount between $5,000 and $1,000,000.");
mortText.setText("");
out.setText("");
}

Answer

Here's the try-catch block that finally worked. It needed to be placed in the actionPerformed method where the rest of my data is. I had another issue where the code kept throwing an exception for any amount that I entered until I figured out that I needed to place the for loop inside of the try block.

try 
{
if((n1 < 5000) || (n1 > 1000000))
  throw new Exception();   

  for (int i = 0; i < term[0] * 12; i++)
  {   
    double interest_paid = n1 * (rate[0] / 12);
    double principal_paid = tr1 - interest_paid;
    n1 = n1 - principal_paid;

    //Prints the results.
    edit.append("\n  " + (i+1) + " \t\t " + (two.format(interest_paid)) 
        + " \t\t " + (two.format(principal_paid)) + " \t\t "
            + (two.format(Math.abs(n1))));            
  }
}
catch (Exception e)
{        
  edit.setText("Please enter an amount between $5,000 and $1,000,000.");       
  mortText.setText("");
  out.setText("");                 
}
Comments