0

If I am not wrong, Lombok's @Data gives the getter, setter and other util methods. Developer can customize its generated methods. And I did that before. But recently I have come across a scenario where I can't customize the mothods. Here my customized method:

@Data
public class DummyClass {

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    private static Calendar cal = new GregorianCalendar();
    
    public String toTimeStr;
    public Long toTime;

     public long getToTime() throws Exception {
        if(this.toTime==null){
            cal.setTime(dateFormat.parse(this.toTimeStr));
            this.toTime = cal.getTimeInMillis();
        }
        return this.toTime;
      }
}

I am getting compilation error: ""java: unreported exception java.lang.Exception; must be caught or declared to be thrown""

But If I add try-catch inside the "getToTime()" method, then it seems fine. Could anyone please give insights that I am missing??

Here the code when try-catch is added inside the getter method.

public long getToTime(){
        try{
           if(this.toTime==null){
            cal.setTime(dateFormat.parse(this.toTimeStr));
            this.toTime = cal.getTimeInMillis();
           }
        }catch (Exception e){

        }
        return this.toTime;
    }

  • 1
    What is `this.toTime`? `this.toTimeStr`? Yes, you're supposed to reduce your code before posting it here, but not to the point where it doesn't compile! It still needs to show the behaviour you're asking about. – Sören Jul 30 '23 at 08:34

1 Answers1

1

I think what’s happening here is the generated equals, hashCode, and toString methods will try to call getToTime. Since these methods can’t throw a checked exception, you’ll need to decide whether to change getToTime so that it doesn’t throw one, or write those methods explicitly to catch it.

I would recommend changing the class to throw an exception when toTimeString is set, so that the error can be handled at the point it is introduced, rather than every time it is accessed subsequently. I would also recommend declaring a more specific exception type.

Tim Moore
  • 8,958
  • 2
  • 23
  • 34
  • Thank you so much. I got it. Getter is accessed in other method like you said. so Setter method is appropriate for throwing exception and handle unexpected event. And I am also using 'ParseException' which is more specific. – Md. Saiful Islam Jul 30 '23 at 08:55