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


Why can't I decrement first, and then throw exception?

public void drive(int laps) {
    // Other driving code omitted for clarity purposes

    if (mBarsCount<1) {
      throw new IllegalArgumentException("Not enough battery remains");
    mBarsCount -= laps;

2 Answers

Hi partha chakraborty,

you should not decrement first, because the new value then is already below 0. However, in this case this might not be fully clear to you because nothing special would happen if it would be possible.

But imagine mBarsCount would blow off a bomb. If you would throw an exception first before altering the value, the bomb wouldn't go off and you would have been warned before.

Now the other way around. You alter the value and make it below 0, the bomb goes off and you get the warning (probably too late).

So what you want to do is to check first if the new value would go below 0. If not, assign that value to mBarsCount. If so, throw an exception without altering the variable.

Thanks Mario Blokland for the clarification.

You are welcome :)