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) Harnessing the Power of Objects Throwing Exceptions

Samson Cohen
Samson Cohen
12,263 Points

Feeling a bit stuck... Can someone help me solve the 'Throwing Exceptions' code challenge in my Java Objects course?

Hi everyone! Been stuck on this for a while now... I think it would give me better clarity on the topic if someone could give me the answer, and of course explain how they got there as well.

Many thanks, Samson

1 Answer

The challenge asks you to throw an IllegalArgumentException in the drive method IF there is not enough energy to compete the laps requested.

Each lap takes one bar of energy to complete and the current number of bars is stored in the variable mBarsCount.

First we need to check IF we can complete the number of laps with an if statement.

if (laps > mBarsCount) { //check if laps is greater the battery level, if so do something
   //do something
}else{ // laps are not greater than battery level, preform drive method normally
  // do something else
}

Now we need to write a piece of code the throw an IllegalArgumentException:

//throw an exception with a specified message
throw new IllegalArgumentException("Not enough battery remains");

Now all together that looks like this in the drive method:

if (laps > mBarsCount) { 
   throw new IllegalArgumentException("Not enough battery remains");
}else{ 
  mBarsCount -= laps;  //code  already in drive method
}
Samson Cohen
Samson Cohen
12,263 Points

Fantastic! Thank you very much for explaining that to me.