Reputation: 927
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.
Upvotes: 1
Views: 1764
Reputation: 24124
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.
This is because a final member variable must be initialized in all code paths of a constructor and must be initialized only once. The only way to avoid this is to decouple the parsing logic from the assignment.
Upvotes: 1
Reputation: 328598
If you are happy to use a default value when there is an exception, you can do something like:
Date temp = null;
try {
temp = dateFormat.parse(timestamp);
} catch (ParseException ex) {
Logger.getLogger(Visit.class.getName()).log(Level.SEVERE, null, ex);
}
this.timestamp = (temp == null ? <some default Date value> : temp);
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 IllegalArgumentException
for example.
Upvotes: 3
Reputation: 120848
Or you could make the constructor "throws" the Exception, for example:
public ToDelete(Date date) throws Exception {
this.date = this.getDate(); //getDate throws the Exception
}
Upvotes: 1