Search code examples
javaexceptionillegalstateexception

how IllegalArgumentExcpetion works in java


I'd like to use IllegalArgumentExcpetion in my script but I can't find any information anywhere. I show what i already have:

public int getId() {
        return id;
    }

    public void setId(int id) {

        if(id<=0) {
            throw new IllegalArgumentException("XX must be a positive integer greater than 0!!");           
        }
        this.m2=m2;
    }

I'd like the IllegalArgumentException show the message “XX must be a positive integer greater than 0!!” and XX means id. My doubt is that I don't know how I can transform the XX into the id


Solution

  • There's nothing special about IllegalArgumentException. You just need to construct the message, e.g. by string concatenation and pass it to the constructor:

    throw new IllegalArgumentException(id + " must be a positive integer greater than 0!!");