-3

How do you write a method that has "throws IllegalArgumentEception" in the method declaration. Such like this one: If I were to only return d if d>0 otherwise throw an IllegalArgumentException, how would I do that? Do you use try{} and catch{} ?

public double getPrice(double d) throws IllegalArgumentException {

}
Deb
  • 2,922
  • 1
  • 16
  • 32
HaakonFlaar
  • 387
  • 2
  • 4
  • 15

2 Answers2

9

You can do that simply at the beginning of the method:

public double getPrice(double d) throws IllegalArgumentException {
     if(d <= 0) {
         throw new IllegalArgumentException();
     }

     // rest of code
}

Also the throws IllegalArgumentException is not really needed in the declaration of the method. This must only be done with checked exceptions. But IllegalArgumentException belongs to the unchecked exceptions.

For more information about those I recommend reading this other question.

Lino
  • 19,604
  • 6
  • 47
  • 65
2

You should check the condition and if it doesn't meet throw the exception

Sample code:

public double getPrice(double d) throws IllegalArgumentException {
    if (d <= 0) {
        throw new IllegalArgumentException("Number is negative or 0");
    }

    //rest of your logic

}

You can learn more about Java Exception here.

Lino
  • 19,604
  • 6
  • 47
  • 65
Deb
  • 2,922
  • 1
  • 16
  • 32