How to Try and Except in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Try and except are perfect when you want to do that might end up in error but don't want the error to stop the program.
The simple case
try:
something()
except:
do_this_if_error()
Here we try the something within the something method but if it does fail for any reason, we run the do_this_if_error method if the something method run fails.
Adding specific exception
Sometimes you don't want your program to fail but still want to know which error is being encountered.
To do so you can print the error known as exception like so:
try:
something()
except Exception as e:
# This time we print the error
print(e)
do_this_if_error()
In this case we do print the error, so that we know what we encounter.
The optimal case
Ideally, a good programmer will want to avoid any loophole in his programm.
You will want to handle every error case individually and correctly.
To do so we can specify the error cases and the code we want to run in any specific case like so:
Conclusion
In the beginning no rush. Keep it simple
It might seem tedious of course.
But it's good practice to handle exception appropriately.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚