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

Israel Palma
Israel Palma
1,456 Points

Confused about where to place the try-catch blocks @Exception throwing exercise

Hi I am a little confused about where should we place the code for the try-catch blocks. Should we place it in the GoKart.java class? I noticed that in the video-lecture the instructor uses it in the Example.java class, that happens to be the main class, that makes sense. But how should we write it from the GoKart.java class? Should the "if" statement be there too?

Israel Palma
Israel Palma
1,456 Points

Never mind I figure it out already. I just used the "if" with the "throw new IllegalArgumentException" statements and It worked. So I guess it can be done from inside the method itself not necessarily from the main method?

Is there a standard or best practice as to where to place this code?

Exception management is quite a large topic. You can throw exceptions in various places and catch them in different places if you don't want to manage errors at the point the exception is created. As you work through the Java courses, there will be more detailed examination of how to handle these things. That will give you an indication of best practice; I'm not expert enough to know the answer to that!

1 Answer

Hi Israel,

You're throwing an exception if a condition is met, yes. So you can use an if for that. Say, for example, if mBarsCount is less than laps parameter, throw the exception - if not, drive the Kart! Something like:

  public void drive(int laps) {
    // Other driving code omitted for clarity purposes
    if(mBarsCount < laps) {
      throw new IllegalArgumentException("Not enough battery remains");
    } else {
      mBarsCount -= laps;
    }
  }

I hope that makes sense.

Steve.

Israel Palma
Israel Palma
1,456 Points

Hi Steve thanks that makes lots of sense. Thank you so much! I do have a new question then:

How do the "throw new IllegalArgumentException("");" and the try-catch blocks have to work together? Do they always need to be together? I assume the try-catch is just to avoid crashing the program with the error and the trhow new is just to make the message for the exception type?

You'll catch that exception in a later challenge. ;-) That'll make more sense than me trying to explain it!!