It's kinda like if-else, but for errors:
Try is exactly what is sounds like, it tries to perform a bit of code.
Normally, when something causes an error, like trying to convert a string with letters to an integer, the script will cease to work and spit out an error.
If you use try-except, Except will catch that error. Usually that's used to display a more helpful error message, but it can also be used to very easily check if something is a valid instance.
Hidden Content
You must
[To see links please register here]
or
[To see links please register here]
to view this content.
The above code produces a TypeError, since "Hello!" is not a valid integer, and the script will never reach the second
print. So to fix that, you would use try-except.
Hidden Content
You must
[To see links please register here]
or
[To see links please register here]
to view this content.
The code will still print out the error, but now it continues on to the final
print. You can also make it silent by changing
print(e) to
pass.
And just so you know, any
try MUST have a matching
except, even if you're not going to use it. An unused
except must, at the very least, contain a
pass statement.
@Kirika; Sometimes docs are a little hard to understand for the uninitiated, get the sand out of your vagina.
@Tear(previous post); The 2.x docs are largely the same as the 3.x docs, and even when they aren't, will usually link to the recommended version at the top. Also, there's a drop-down at the top of all doc pages that will move you to the valid page for your selected version.