How to Try and Except in Python

1 min readFundamentalsErrorsGetting Started
7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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:

try:
	something()
except ZeroDivisionError:
	# This time we print the error
	print("There was a division by zero")
except NameError:
	print("The variable doesn't exist")
except TypeError:
	print("There was a cast problem")
else:
	do_this_if_error()
Do something specific for every exception

Conclusion

In the beginning no rush. Keep it simple

It might seem tedious of course.

But it's good practice to handle exception appropriately.

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.