Search code examples
javaoopsettergettergetter-setter

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


To be more specific, I want to write a code that throws IllegalArgumentException if the given value is negative. Should I include this code inside of setter/constructor or should I check the value when the appropriate method is called? (Eg: 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 don't recall a single case that a setter throws an exception as above. But I'm curious if it is good / bad.


Solution

  • The best approach is to make your object immutable, get rid of your setters and throws your exception in the constructor otherwise whatever the way you choose, in case of an error, you have a high risk to have your object in an inconsistent state which will cause hard bug to find. For a better understanding, please read this especially the section related to Failure Atomicity.