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 trialKarlyn Gibson
9,176 PointsWhy does it jump a line of code in the try block?
When the code executes, the video says, if there is an exception thrown in game.applyGuess(guess), that the code will jump over the second statement in the try block...
try { isHit = game.applyGuess(guess); isAcceptable = true; } catch(IllegalArgumentException iae) { System.out.println("%s. Please try again. %n", iae.getMessage()); }
Why does it automatically jump over switching isAcceptable to true? Is this specific to a try/catch block?
2 Answers
andren
28,558 PointsIt jumps over it because an exception was thrown, and it's not just one line. Any code that is placed after an exception throwing line in a try
block will be skipped.
The purpose of a try/catch
block is that the try
block will essentially be on the lookout for exceptions thrown by the code within it. And once one occurs will automatically pass the exception to whatever catch block has been setup to deal with the exception. Once that happens the job of the try/catch
block is done so the remaining code is not ran.
If you wanted the isAcceptable
line to run regardless of whether the applyGuess
threw an error or not then you could simply place it outside of the try
block like this:
try {
isHit = game.applyGuess(guess);
} catch(IllegalArgumentException iae) {
System.out.println("%s. Please try again. %n", iae.getMessage());
}
isAcceptable = true;
Generally you should only place code that might throw exceptions and code that should only run if no exception occurred from that code within the try
block. Any code you want to run regardless should be placed outside try
blocks.
In the example you provided the isAcceptable
variable is likely there to signal if the applyGuess
actually ran without issues. So having it inside of the try
block makes sense.
Aytuğ HAN
641 PointsAfter an exception was thrown any code after that line will be skipped. So only if isHit = game.applyGuess(guess) is valid isAcceptable will be true.
class TryCatch {
public static void main(String args[]) {
try {
System.out.println("You can see me.");
int number = 50 / 0;
System.out.println("You can't see me.");
} catch (ArithmeticException ae) {
System.out.println("Error: You can't divide a number by zero");
}
}
}
Output :
You can see me.
Error: You can't divide a number by zero