How to use the Try and Except statement in Python

1 min readFundamentalsBuilt-inExceptions
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.

In Python, the try and except statement allows you to handle errors and exceptions in your code in a clean and organised way. The try block contains the code that might raise an exception, and the except block contains the code that will be executed if an exception is raised.

Here's an example of how you can use the try and except statement to handle a ZeroDivisionError:

try:
    x = 5 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")

In this example, the code in the try block attempts to divide 5 by 0 which raises a ZeroDivisionError. The code in the except block then runs, and the message "You can't divide by zero!" is printed.

You can also use the finally block to specify code that should be executed no matter if an exception is raised or not.

try:
    x = 5 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This will run no matter what.")

You can also use the else block to specify code that should be executed if an exception is not raised.

try:
    x = 5 / 2
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print(f"The result is {x}")

You can also use raise statement to raise an exception explicitly

def raise_exception():
    raise Exception("This is an exception")
try:
    raise_exception()
except Exception as e:
    print(e)

It's worth noting that try and except statements can be nested, you can also use as keyword to assign an exception to a variable and use it later, also you can use multiple except blocks to handle different types of exceptions.

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.