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

Python Python Basics All Together Now Handle Exceptions

Luis Walderdorff
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Luis Walderdorff
Full Stack JavaScript Techdegree Graduate 27,070 Points

How does the else statement work in this example?

I don't understand why exactly the else statement makes the function loop again when we have an error, because there is no if statement preceding it. Does the except statement count as the if in this example and if there is no error, only then it runs the rest of the code, or what is the else in reference to?

1 Answer

Luis,

I am not looking at the code you are referring to, but I assume you are asking about an else clause after a try...except statement in Python. If that's the case, then I can tell you the else clause is used to contain statements that you only want to execute if the try clause succeeds. You can think of it as a "no-exception" clause. Of course, if, as part of the exception handling you rethrow, break, or return, then you really don't need an else clause. But you do need else if you don't exit the block and you want some statements to execute only if the try succeeds.

Hope this helps.

Cheers, —Steve

Moderator Edit: Moved reply from Comments to Answers