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
Scottie Crowe
4,965 PointsCan someone explain to me how try/except statements work?
My understanding of try/except statements is this: 1. code between try and except is evaluated and executed, except if an error is thrown 2. If an error occurs, the code after except is evaluated and executed
What happens if neither 1 or 2 work? Is an error thrown and then added to the except statement?
Is the try/except statement used when we anticipate possible errors to occur?
I need some help/clarification for how this works and why it is used.
Thanks!
1 Answer
Pedro Cabral
33,586 PointsIs the try/except statement used when we anticipate possible errors to occur?
This is correct.
Imagine you write a program that divides the number 10 by whichever number gets inputted by the user. So your code is something like: 10 / input(). What if the user inputs a string? You can't divide by a string, so your program will break. What if the user inputs a number, but that number is 0? You can't divide by zero, your program will break. In this case for two very different reasons. You can create an exception block that will catch any error, buy you can also be more specific and handle each error individually.
You want your program to run smoothly, so as you said you want to anticipate errors. In the case above, you will try to execute the program but if an error occurs you will want to catch it (other languages use this word, "catch") on your except block. In this case, whatever is inside the except block will run, and your code won't crash because you handled the error.
Additionally, there is also something called else block, which will run after the try, only if no exceptions were thrown.