Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Delivering the MVP Validation

Mike B
Mike B
10,424 Points

Why use a throw IllegalArgumentException instead of simply using an if() statement?

I'm not sure why we would throw an IllegalArgumentException while asking for a guess. Why not just use an if statement that looks to make sure the letter we are guessing is a letter and also a letter not already guessed with a system.out.print prompt asking for the proper input?

We did that when we were looking for bad words in the mad libs example

3 Answers

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hey Mike,

the IllegalArgumentException proofs the arguments that are passed into a method. An if statement can proof the variables inside a class or method, but it is not for arguments.

Here an example:

public int calculateFactorial(int n) {//n is an argument
  if (n < 0) {
    throw new IllegalArgumentException("n must be positive");
}
  if (n >= 60) {
    throw new IllegalArgumentException("n must be < 60");
 }     
}

So your n must be between 0 and 60

The IllegalArgumentExceptionI is thrown when a method is taking an arguments outside a particular range, e.g. only positive numbers, numbers not Strings etc.

Mike B
Mike B
10,424 Points

I feel like a moron...of course....Argument is right in the name! Thank you....that makes perfect sense

Marina Alenskaja
Marina Alenskaja
9,320 Points

Great answer!

And Mike, I was wondering about that too so don't feel too bad ;-) Almost everything is questionable when learning a new language!

Antone Bagnall
Antone Bagnall
6,744 Points

Hi Mike

An if statement cannot be used to check if an error occurs, the illegal argument exception is used to prevent the program crashing by giving the user a chance to fix the error.

If you tried to use an if statement, it couldn't prevent the program from crashing.

Hope that clears things up!

Antone.

Mike B
Mike B
10,424 Points

Sorry, I should have used a do/while loop as an example. How does an illegal argument exception differ from that? Couldn't we use that in place for the same result?