When a class has all final
fields, the compiler ensures that the object’s state remains constant. It also enforces a clear design
intent of immutability, making the class easier to reason about and use correctly.
Exceptions are meant to represent the application’s state at the point at which an error occurred. Making all fields in an Exception
class final
ensures that these class fields do not change after initialization.
Noncompliant code example
public class MyException extends Exception {
private int status; // Noncompliant
public MyException(String message) {
super(message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
Compliant solution
public class MyException extends Exception {
private final int status; // Compliant
public MyException(String message, int status) {
super(message);
this.status = status;
}
public int getStatus() {
return status;
}
}