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

Обработка Исключений


Когда программируешь, ошибки случаются. Это просто факт жизни. Возможно, пользователь ввел неправильные данные. Может быть, сетевой ресурс был недоступен. Возможно, программа исчерпала память. Или даже программист мог допустить ошибку!

Решением Python для ошибок являются исключения. Вы могли раньше видеть исключение.

print(a)

#ошибка
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Упс! Забыл присвоить значение переменной 'a'.

Но иногда вы не хотите, чтобы исключения полностью останавливали программу. Вы можете захотеть сделать что-то особенное, когда возникает исключение. Это делается в блоке try/except.

Вот тривиальный пример: Предположим, вы перебираете список. Вам нужно перебрать 20 чисел, но список сформирован из ввода пользователя и может не содержать 20 чисел. После того, как вы достигли конца списка, вы просто хотите, чтобы остальные числа интерпретировались как 0. Вот как это можно сделать:

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()

Вот, это было не так сложно! Вы можете делать это с любым исключением. Для получения более подробной информации об обработке исключений посмотрите Python Docs

Exercise

Handle all the exception! 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