Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

Zpracování výjimek


When programming, errors occur. It's a fact of life. Perhaps the user provided incorrect input. Maybe a network resource was unavailable. Perhaps the program ran out of memory. Or maybe the programmer even made a mistake!

Python's solution to errors are exceptions. You might have seen an exception before.

print(a)

#error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Oops! Forgot to assign a value to the variable 'a'.

But sometimes, you don't want exceptions to completely stop the program. You might want to do something special when an exception is raised. This is done in a try/except block.

Here's a trivial example: Suppose you're iterating over a list. You need to iterate over 20 numbers, but the list is constructed from user input and might not contain 20 numbers. After reaching the end of the list, you want the remaining numbers to be interpreted as 0. Here's how you could do that:

def do_stuff_with_number(n):
    print(n)

def catch_this():
    the_list = (1, 2, 3, 4, 5)

    for i in range(20):
        try:
            do_stuff_with_number(the_list[i])
        except IndexError: # Raised when accessing a non-existing index of a list
            do_stuff_with_number(0)

catch_this()

There, that wasn't too difficult! You can do that with any exception. For more details on handling exceptions, look no further than the Python Docs

Exercise

Handle all the exceptions! Think back to the previous lessons to return the last name of the actor.

# Setup actor = {"name": "John Cleese", "rank": "awesome"} # Function to modify!!! def get_last_name(): return actor["last_name"] # Test code get_last_name() print("All exceptions caught! Good job!") print("The actor's last name is %s" % get_last_name()) actor = {"name": "John Cleese", "rank": "awesome"} def get_last_name(): return actor["name"].split()[1] get_last_name() print("All exceptions caught! Good job!") print("The actor's last name is %s" % get_last_name()) test_output_contains("Cleese") test_output_contains("All exceptions caught! Good job!") test_output_contains("The actor's last name is Cleese") success_msg("Great work!")

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy