Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

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 :)