I am very new to java and I am having some issues with getting my code to catch and display an exception has been caught. The idea of the code is to throw an exception if any of the values of Loan are zero or less. Below is my code, which does not have any output for an exception, despite the fact that loan1 and loan3 have nothing but zeros. Any help would be appreciated by a six week newbie. Thanks!
package loan;
public class Loan {
public static void main(String[] args) {
try {
Loan loan1 = new Loan(0, 0, 00.00);
Loan loan2 = new Loan(5, 10, 500.00);
Loan loan3 = new Loan(0, 0, 0.00);
}
catch (IllegalArgumentException ex) {
System.out.println(ex);
}
}
// declare variables for Loan class
double annualInterestRate;
int numberOfYears;
double loanAmount;
private java.util.Date loanDate;
// Loan class
public Loan() {
}
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
public double getAnnualInterestRate() throws IllegalArgumentException { //exception added if value is zero or less, added on each variable
if (annualInterestRate >= 0)
throw new IllegalArgumentException("Interest rate cannot be zero or negative.");
else
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public int getNumberOfYears() throws IllegalArgumentException {
if (numberOfYears >= 0)
return numberOfYears;
else
throw new IllegalArgumentException("Number of years cannot be zero");
}
public void setNumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
public double getLoanAmount() throws IllegalArgumentException {
if (loanAmount >= 0)
return loanAmount;
else
throw new IllegalArgumentException("Loan amount cannot be zero");
}
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
public double getMonthlyPayment() {
double monthlyInterestRate = annualInterestRate/1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1/(1 + monthlyInterestRate), numberOfYears *12)));
return monthlyPayment;
}
public double getTotalPayment() {
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
public java.util.Date getLoanDate() {
return loanDate;
}
}
You only throw an exception in the “getter” methods, like
getAnnualInterestRate, etc. But you never call them. Either call some of your getters, or (better) throw an exception from the constructor and the setter methods (because this is where you’re setting the values).