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.

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