I have a class with two constructors – one accepts a Date object and the other attempts to create a date object based upon a given timestamp string. The caveat of this is that the conversion to a Date object can throw an exception. I’m getting the ‘variable timestamp might not have been initialized’ error.
First constructor:
public Visit(Date timestamp) {
this.timestamp = timestamp;
}
Second constructor (the one that produces the error):
public Visit(String timestamp) {
try {
this.timestamp = dateFormat.parse(timestamp);
} catch (ParseException ex) {
Logger.getLogger(Visit.class.getName()).log(Level.SEVERE, null, ex);
}
}
I’ve tried adding the initialization of this.timestamp to the finally statement of the try but this then gives an error that the variable may already have been initialized.
If you are happy to use a default value when there is an exception, you can do something like:
If not, then you could throw an exception from your constructor. Typically, if the argument of your constructor is not valid, you could rethrow an
IllegalArgumentExceptionfor example.