I am working on something that should be fairly simple. I have 95% of my program working, but one piece is still not fulfilling the requirement. (FYI, this is for a homework assignment, but I will prove that I have put good effort into it before coming here.)
The piece of the assignment:
* The ProductionWorker class should throw an exception named InvalidPayRate when it receives a negative number for the hourly pay rate or if the data entered is not numeric.
I have my InvalidPayRate logic for catching negative numbers, but I am not too sure how to ensure that the input is numeric. Here is the relevant code:
InvalidPayRate.java
public class InvalidPayRate extends Exception {
public InvalidPayRate(){
super("Error: Invalid Pay Rate.");
}
}
ProductionWorker.java
void setHourlyPayRate(double rate) throws InvalidPayRate
{
if (rate < 0.0){
throw new InvalidPayRate();
}
this.hourlyPayRate = rate;
}
test.java (this is within a main function)
//Set Rate details
try{
worker.setHourlyPayRate(-15.00);
System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
System.out.println(e.getMessage());
}
try{
worker.setHourlyPayRate(20.00);
System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
System.out.println(e.getMessage());
}
String testRate = "1v2.65";
try{
double rate = Double.parseDouble(testRate);
worker.setHourlyPayRate(rate);
System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
System.out.println(e.getMessage());
}
Right now, 2 of the 3 tests are working… the Valid entry, the negative number entry (returns my custom error) but my non-numeric entry is not working… it gives the standard NumberFormatException error.
How can I perform a logical test to ensure that MY CUSTOM ERROR gets thrown instead of the NumberFormatException?
1
The error is thrown from Double.parseDouble
, in other words outside of your code, by the time setHourlyPayRate
gets called you know it’s a valid double. The conversion from string to double is not your problem™.
If you really want to throw your custom exception then you need to wrap the conversion in a try catch and rethrow the custom exception:
String testRate = "1v2.65";
try{
double rate;
try{
rate = Double.parseDouble(testRate);
} catch (NumberFormatException e) {
throw new InvalidPayRate();
}
worker.setHourlyPayRate(rate);
System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
System.out.println(e.getMessage());
}
There is one input you don’t guard against though and that is Double.NaN
which you can test for with Double.isNan
.
if (Double.isNaN(rate) || rate < 0.0){
throw new InvalidPayRate();
}
8