Is it good practice to throw Exception inside setters in Java?

To be more specific, I want to write code that throws an IllegalArgumentException if the given value is negative. Should I include this code inside setter / constructor or should I check the value when calling the appropriate method? (For example: start() , init() , print() or run() . Whatever.)

My code (simplified):

 public class LLUAlgorithm { private int temperature; public int getTemperature() { return temperature; } public void setTemperature(int temperature) { if (temperature < 0) throw new IllegalArgumentException("can't be smaller than 0.") this.temperature = temperature; } public void run() { ... } 

I do not remember a single case when the setter throws an exception, as indicated above. But I'm curious if this is good / bad.

+5
source share
1 answer

The best approach is to make your object immutable , get rid of your setters and throw an exception in the constructor, otherwise, no matter how you choose, in case of an error you have a high risk of your object being in an inconsistent state, which can cause a serious error. For a better understanding, please read this , especially the Failure Atomicity section.

+4
source

All Articles