Search code examples
javalombokgetter-setter

Lombok gives java: unreported exception java.lang.Exception; must be caught or declared to be thrown


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;
    }


Solution

  • 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.