Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 997
leventunver Avatar asked May 07 '16 19:05

leventunver


1 Answers

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.

like image 148
Nicolas Filotto Avatar answered Nov 15 '22 14:11

Nicolas Filotto