1

我有一个带有两个构造函数的类——一个接受一个Date对象,另一个尝试根据给定的时间戳字符串创建一个日期对象。需要注意的是,转换为Date对象可能会引发异常。我收到“变量时间戳可能尚未初始化”错误。

第一个构造函数:

public Visit(Date timestamp) {
    this.timestamp = timestamp;
}

第二个构造函数(产生错误的那个):

public Visit(String timestamp) {
    try {
        this.timestamp = dateFormat.parse(timestamp);
    } catch (ParseException ex) {
        Logger.getLogger(Visit.class.getName()).log(Level.SEVERE, null, ex);
    }
}

我已经尝试将初始化添加this.timestampfinally语句中,try但这会给出一个错误,即变量可能已经被初始化。

4

3 回答 3

3

如果您乐于在出现异常时使用默认值,则可以执行以下操作:

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.

于 2012-08-25T15:08:12.270 回答
1

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
}
于 2012-08-25T15:11:32.993 回答
1

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.

于 2012-08-25T15:12:42.220 回答