Значения исключений и ошибок в python

Standard Exceptions

Here is a list of Standard Exceptions available in Python. −

Sr.No. Exception Name & Description
1

Exception

Base class for all exceptions

2

StopIteration

Raised when the next() method of an iterator does not point to any object.

3

SystemExit

Raised by the sys.exit() function.

4

StandardError

Base class for all built-in exceptions except StopIteration and SystemExit.

5

ArithmeticError

Base class for all errors that occur for numeric calculation.

6

OverflowError

Raised when a calculation exceeds maximum limit for a numeric type.

7

FloatingPointError

Raised when a floating point calculation fails.

8

ZeroDivisonError

Raised when division or modulo by zero takes place for all numeric types.

9

AssertionError

Raised in case of failure of the Assert statement.

10

AttributeError

Raised in case of failure of attribute reference or assignment.

11

EOFError

Raised when there is no input from either the raw_input() or input() function and the end of file is reached.

12

ImportError

Raised when an import statement fails.

13

KeyboardInterrupt

Raised when the user interrupts program execution, usually by pressing Ctrl+c.

14

LookupError

Base class for all lookup errors.

15

IndexError

Raised when an index is not found in a sequence.

16

KeyError

Raised when the specified key is not found in the dictionary.

17

NameError

Raised when an identifier is not found in the local or global namespace.

18

UnboundLocalError

Raised when trying to access a local variable in a function or method but no value has been assigned to it.

19

EnvironmentError

Base class for all exceptions that occur outside the Python environment.

20

IOError

Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.

21

OSError

Raised for operating system-related errors.

22

SyntaxError

Raised when there is an error in Python syntax.

23

IndentationError

Raised when indentation is not specified properly.

24

SystemError

Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.

25

SystemExit

Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.

26

TypeError

Raised when an operation or function is attempted that is invalid for the specified data type.

27

ValueError

Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.

28

RuntimeError

Raised when a generated error does not fall into any category.

29

NotImplementedError

Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

8.5. Исключения, определяемые пользователем

В программах можно создавать свои собственные исключения, создав новый класс исключения (см. Классы для подробной информации о классах Python). Исключения должны быть обычно получены от класса Exception (docs.python.org/3/library/exceptions.html#Exception), прямо или опосредованно.

Могут быть определены классы исключений, которые делают любое, что делают другие классы, но обычно оставляют простыми, часто только предлагающими ряд атрибутов, которые позволяют информации об ошибке быть извлеченной обработчиками исключения. При создании модуля, который может возбуждать несколько различных ошибок, обычной практикой является создание базового класса для исключений, определенных модулем, и подкласса для создания конкретных классов исключений для различных условий ошибок:

Большинство исключений определяются с именами, которые заканчиваются на «Error», похоже на именование стандартных исключений.

Многие стандартные модули определяют свои собственные исключения для сообщения об ошибках, которые могут возникнуть в функциях, которые в них определены. Более подробная информация о классах представлена в главе Классы.

Traceback

В большой программе исключения часто возникают внутри. Чтобы упростить программисту понимание ошибки и причины такого поведения Python предлагает Traceback или в сленге — трэйс. Каждое исключение содержит краткую информацию, но при этом полную, информацию о месте появления ошибки. По трэйсу найти и исправить ошибку становится проще.

Рассмотрим такой пример:

Traceback (most recent call last):
  File "/home/username/Develop/test/app.py", line 862, in _handle
    return route.call(**args)
  File "/home/username/Develop/test/app.py", line 1729, in wrapper
    rv = callback(*a, **ka)
  File "/home/username/Develop/test/__init__.py", line 76, in wrapper
    body = callback(*args, **kwargs)
  File "/home/username/Develop/test/my_app.py", line 16, in index
    raise Exception('test exception')

В данном примере четко видно, какой путь исполнения у программы. Смотрим снизу вверх и по шагам пониманием, как же мы докатились до такого исключения.

Рассмотрим какие еще встречаются комментарии к исключениям:

2 + '1'

Traceback (most recent call last):
  File "", line 1, in
    2 + '1'
TypeError unsupported operand type(s) for + 'int' and 'str'

В данном примере при попытке сложить целое число и строку мы получаем исключение TypeError. В описании сразу же становится ясно, что же мы не так написали.

int('qwerty')

Traceback (most recent call last):
  File "", line 1, in
    int('qwerty')
ValueError invalid literal for int() with base 10 'qwerty'

Приведение строчки к целому числу приводит к исключению ValueError.

В трэйсе этих двух примеров можно прочесть, что в таком-то файле на такой-то строчке есть ошибки.

На этом список встроенных исключений не заканчивается, в следующем разделе рассмотрены основные исключения и причины их возникновения.

8.1. Синтаксические ошибки

Синтаксические ошибки (Syntax Errors), также известны как ошибки грамматического разбора (parsing errors), являются, пожалуй, наиболее распространенным видом жалоб пока вы все еще изучаете Python:

Синтаксический анализатор (parser — парсер) повторяет ошибочную строку и отображает маленькую «стрелку», указывая тем самым, что в предшествующей строке была обнаружена ошибка. Ошибка вызвана (или хотя бы обнаружилась) объектом предшествующим стрелке: в примере, ошибка обнаружена в функции , так как перед ней отсутствует двоеточие (). Имя файла и номер строки выводятся, чтобы вы знали, где искать в случае, если ввод был получен из скрипта.

Пример вложенных блоков try-except

У нас могут быть вложенные блоки try-except в Python. В этом случае, если во вложенном блоке try возникает исключение, для его обработки используется вложенный блок except. В случае, если вложенный объект except не может его обработать, для обработки исключения используются внешние блоки except.

x = 10
y = 0

try:
    print("outer try block")
    try:
        print("nested try block")
        print(x / y)
    except TypeError as te:
        print("nested except block")
        print(te)
except ZeroDivisionError as ze:
    print("outer except block")
    print(ze)

Вывод:

outer try block
nested try block
outer except block
division by zero

Summing Up

After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:

  • allows you to throw an exception at any time.
  • enables you to verify if a certain condition is met and throw an exception if it isn’t.
  • In the clause, all statements are executed until an exception is encountered.
  • is used to catch and handle the exception(s) that are encountered in the try clause.
  • lets you code sections that should run only when no exceptions are encountered in the try clause.
  • enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Free PDF Download: Python 3 Cheat Sheet

Counter

Модуль collections также предоставляет нам небольшой аккуратный инструмент, который поддерживает быстрый и удобный в пользовании калькулятор. Этот инструмент называется Counter. Вы можете запустить его против большинства итерируемых. Давайте попробуем взглянуть на него в строке.

Python

from collections import Counter

a = Counter(‘superfluous’)

# Counter({‘u’: 3, ‘s’: 2, ‘e’: 1, ‘l’: 1, ‘f’: 1, ‘o’: 1, ‘r’: 1, ‘p’: 1})
print(a)

counter = Counter(‘superfluous’)
print(counter) # 3

1
2
3
4
5
6
7
8
9

fromcollectionsimportCounter

a=Counter(‘superfluous’)

 
# Counter({‘u’: 3, ‘s’: 2, ‘e’: 1, ‘l’: 1, ‘f’: 1, ‘o’: 1, ‘r’: 1, ‘p’: 1})

print(a)

counter=Counter(‘superfluous’)

print(counter’u’)# 3

В данном примере мы импортировали Counter из модуля collections и передали его строке. Это возвращает нам объект Counter, который является наследуемым классом словаря Python. Когда мы запускаем эту же команду, но назначаем её счетчик переменной, чтобы доступ к словарю был несколько проще. В данном случае, мы видим, что буква “u” встречается три раза в нашем примере. Класс Counter предоставляет несколько методов, которые могут вас заинтересовать. Например, вы можете вызывать элементы, которые будут выполнять итерацию над элементами, расположенными в словаре, но в произвольном порядке. Вы можете подумать, что эта функция является своего рода скремблером, так как выдача в этом случае представлена как скремблированная версия строки.

Python

print(list(counter.elements()))
#

1
2

print(list(counter.elements()))

#

Еще один полезный метод это most_common. Вы можете спросить Counter о том, какие объекты являются наиболее распространенными, передав число, отображающее наиболее часто повторяющие объекты “n”:

Python

print(counter.most_common(2))
#

1
2

print(counter.most_common(2))

#

Здесь мы попросили наш Counter выяснить, какие два объекта являются наиболее повторяемыми. Как вы видите, мы получили список кортежей, в котором указано, что “u” встречается 3 раза, а “s” – два раза. Еще один метод, который я хотел бы рассмотреть, это метод subtract.

Метод subtract принимает итерируемые или отражения и использует этот аргумент для вычета. Это немного проще понять, если взглянуть на код:

Python

from collections import Counter

counter_one = Counter(‘superfluous’)

# Counter({‘u’: 3, ‘s’: 2, ‘e’: 1, ‘l’: 1, ‘f’: 1, ‘o’: 1, ‘r’: 1, ‘p’: 1})
print(counter_one)

counter_two = Counter(‘super’)
counter_one.subtract(counter_two)

print(counter_one)
# Counter({‘u’: 2, ‘l’: 1, ‘f’: 1, ‘o’: 1, ‘s’: 1, ‘e’: 0, ‘r’: 0, ‘p’: 0})

1
2
3
4
5
6
7
8
9
10
11
12

fromcollectionsimportCounter

counter_one=Counter(‘superfluous’)

 
# Counter({‘u’: 3, ‘s’: 2, ‘e’: 1, ‘l’: 1, ‘f’: 1, ‘o’: 1, ‘r’: 1, ‘p’: 1})

print(counter_one)

counter_two=Counter(‘super’)

counter_one.subtract(counter_two)

print(counter_one)

# Counter({‘u’: 2, ‘l’: 1, ‘f’: 1, ‘o’: 1, ‘s’: 1, ‘e’: 0, ‘r’: 0, ‘p’: 0})

Здесь мы создали заново наш первый счетчик и вывели его, чтобы узнать, что же в нем находится. Далее мы создали второй объект Counter. Наконец, мы вычли второй счетчик из первого. Если вы внимательно рассмотрите выдачу в конце, вы увидите, что количество букв для пяти объектов было уменьшено на одну. Как я заметил в начале раздела, вы можете использовать Counter против любых итерируемых или сопоставлений, так что вам не нужно использовать только строки. Вы можете также передать его кортежам, словарям и спискам! Попробуйте на практике, чтобы увидеть, как он работает с разными типами данных:
Теперь мы готовы к тому, чтобы перейти к defaultdict!

Some Built-In Warning Classes

The Warning class is the base class for all the warnings. It has the following sub-classes.

  • BytesWarning – bytes, and buffer related warnings, mostly related to string conversion and comparison.
  • DeprecationWarning – warning about deprecated features
  • FutureWarning – base class for warning about constructs that will change semantically in the future.
  • ImportWarning – warning about mistakes in module imports
  • PendingDeprecationWarning – warning about features that will be deprecated in future.
  • ResourceWarning – resource usage warnings
  • RuntimeWarning – warnings about dubious runtime behavior.
  • SyntaxWarning – warning about dubious syntax
  • UnicodeWarning – Unicode conversion-related warnings
  • UserWarning – warnings generated by the user code

5. Ключевое слово raise в Python

Иногда нужно будет разбираться с проблемами с помощью вызова исключения. Обычная инструкция тут не сработает.

Разберемся на примере операции деления:

Здесь ввод пользователя в переменные и конвертируется в целые числа. Затем проверяется, равна ли нулю. Если да, то вызывается .

Что будет, если то же самое добавить в блоки try-except? Добавим следующее в код. Если запустить его, ввести 1 и 0, будет следующий вывод:

Рассмотрим еще несколько примеров, прежде чем двигаться дальше:

a. Raise без определенного исключения в Python

Можно использовать ключевое слово и не указывая, какое исключение вызвать. Оно вызовет исключение, которое произошло. Поэтому его можно использовать только в блоке .

b. Raise с аргументом в Python

Также можно указать аргумент к определенному исключению в . Делается это с помощью дополнительных деталей исключения.

Exception hierarchy¶

The class hierarchy for built-in exceptions is:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Задания для самоподготовки

1. Напишите
программу ввода натуральных чисел через запятую и преобразования этой строки в
список целых чисел. (Используйте здесь функцию map для
преобразования элементов последовательности строк в последовательность чисел).
Реализовать обработку возможных исключений при таком преобразовании.

2. Написать
функцию вычисления среднего арифметического элементов переданного ей списка.
Реализовать обработку возможных исключений при ее работе.

3. Написать
функцию-генератор (с использованием оператора yield) для удаления
произвольного элемента из множества (с помощью метода pop()). Функция
должна возвращать значение удаленного элемента. Реализовать обработку возможных
исключений при ее работе.

Видео по теме

Python 3 #1: установка и запуск интерпретатора языка

Python 3 #2: переменные, оператор присваивания, типы данных

Python 3 #3: функции input и print ввода/вывода

Python 3 #4: арифметические операторы: сложение, вычитание, умножение, деление, степень

Python 3 #5: условный оператор if, составные условия с and, or, not

Python 3 #6: операторы циклов while и for, операторы break и continue

Python 3 #7: строки — сравнения, срезы строк, базовые функции str, len, ord, in

Python 3 #8: методы строк — upper, split, join, find, strip, isalpha, isdigit и другие

Python 3 #9: списки list и функции len, min, max, sum, sorted

Python 3 #10: списки — срезы и методы: append, insert, pop, sort, index, count, reverse, clear

Python 3 #11: списки — инструмент list comprehensions, сортировка методом выбора

Python 3 #12: словарь, методы словарей: len, clear, get, setdefault, pop

Python 3 #13: кортежи (tuple) и операции с ними: len, del, count, index

Python 3 #14: функции (def) — объявление и вызов

Python 3 #15: делаем «Сапер», проектирование программ «сверху-вниз»

Python 3 #16: рекурсивные и лямбда-функции, функции с произвольным числом аргументов

Python 3 #17: алгоритм Евклида, принцип тестирования программ

Python 3 #18: области видимости переменных — global, nonlocal

Python 3 #19: множества (set) и операции над ними: вычитание, пересечение, объединение, сравнение

Python 3 #20: итераторы, выражения-генераторы, функции-генераторы, оператор yield

Python 3 #21: функции map, filter, zip

Python 3 #22: сортировка sort() и sorted(), сортировка по ключам

Python 3 #23: обработка исключений: try, except, finally, else

Python 3 #24: файлы — чтение и запись: open, read, write, seek, readline, dump, load, pickle

Python 3 #25: форматирование строк: метод format и F-строки

Python 3 #26: создание и импорт модулей — import, from, as, dir, reload

Python 3 #27: пакеты (package) — создание, импорт, установка (менеджер pip)

Python 3 #28: декораторы функций и замыкания

Python 3 #29: установка и порядок работы в PyCharm

Python 3 #30: функция enumerate, примеры использования

Python try with else clause

In some situations, you might want to run a certain block of code if the code block inside ran without any errors. For these cases, you can use the optional keyword with the statement.

Note: Exceptions in the else clause are not handled by the preceding except clauses.

Let’s look at an example:

Output

If we pass an odd number:

Enter a number: 1
Not an even number!

If we pass an even number, the reciprocal is computed and displayed.

Enter a number: 4
0.25

However, if we pass 0, we get as the code block inside is not handled by preceding .

Enter a number: 0
Traceback (most recent call last):
  File "<string>", line 7, in <module>
    reciprocal = 1/num
ZeroDivisionError: division by zero

The try and except Block: Handling Exceptions

The and block in Python is used to catch and handle exceptions. Python executes code following the statement as a “normal” part of the program. The code that follows the statement is the program’s response to any exceptions in the preceding clause.

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The clause determines how your program responds to exceptions.

The following function can help you understand the and block:

The can only run on a Linux system. The in this function will throw an exception if you call it on an operating system other then Linux.

You can give the function a using the following code:

The way you handled the error here is by handing out a . If you were to run this code on a Windows machine, you would get the following output:

You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the into something that would generate an informative message, like so:

Execute this code on a Windows machine:

When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful.

What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw.

The following code is an example where you capture the and output that message to screen:

Running this function on a Windows machine outputs the following:

The first message is the , informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.

In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the exception and printed it to screen.

Here’s another example where you open a file and use a built-in exception:

If file.log does not exist, this block of code will output the following:

This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:

To catch this type of exception and print it to screen, you could use the following code:

In this case, if file.log does not exist, the output will be the following:

You can have more than one function call in your clause and anticipate catching various exceptions. A thing to note here is that the code in the clause will stop as soon as an exception is encountered.

Warning: Catching hides all errors…even those which are completely unexpected. This is why you should avoid bare clauses in your Python programs. Instead, you’ll want to refer to specific exception classes you want to catch and handle. You can learn more about why this is a good idea in this tutorial.

Look at the following code. Here, you first call the function and then try to open a file:

If the file does not exist, running this code on a Windows machine will output the following:

Inside the clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:

Here are the key takeaways:

  • A clause is executed up until the point where the first exception is encountered.
  • Inside the clause, or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare clauses.

Оператор try … except

Скрыть рекламу в статье

Оператор try … except

Оператор try … except имеет вид:

try

операторы

except

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

end;

Блок try называется защищаемым блоком. Если при выполнении программы в нем происходит ошибка, то он завершается и выполнение передается блоку except. Если исключение обрабатывается в блоке except, то после его обработки программа продолжает выполняться с оператора, следующего за try … except … end. Если исключение остается необработанным и имеется объемлющий блок try, то выполнение передается его блоку except. Если объемлющего блока try нет, то программа завершается с ошибкой. Наконец, если в блоке try ошибки не произошло, то блок except игнорируется и выполнение программы продолжается дальше.

Если в процессе обработки исключения (в блоке except) произошло другое исключение, то текущий блок except завершается, первое исключение считается необработанным и обработка нового исключения передается объемлющему блоку try. Таким образом, в каждый момент времени существует максимум одно необработанное исключение.

Блок обработки исключений представляет собой либо последовательность операторов, разделенных точкой с запятой, либо последовательность обработчиков исключений вида

on имя: типdo оператор

Обработчики разделяются символом ‘;’, после последнего обработчика также может следовать символ ‘;’. Здесь тип — тип исключения (должен быть производным от стандартного типа Exception), имя — имя переменной исключения (имя с последующим двоеточием может быть опущено). В первом случае при обработке исключения выполняются все операторы из блока except. Во втором случае среди обработчиков осуществляется поиск типа текущего исключения (обработчики перебираются последовательно от первого до последнего), и если обработчик найден, то выполняется соответствующий оператор обработки исключения, в противном случае исключение считается необработанным и передается объемлющему блоку try. В последнем случае после всех обработчиков on может идти ветвь else, которая обязательно обработает исключение, если ни один из обработчиков не выполнился.

Следует обратить внимание, что имя переменной исключения в разных обработчиках может быть одинаковым, т.е. оно локально по отношению к обработчику

Поиск типа исключения в обработчиках производится с учетом наследования: исключение будет обработано, если оно принадлежит к указанному в обработчике типу или производному от него. Поэтому принято записывать вначале обработчики производных классов, а затем — обработчики базовых (в противном случае обработчик исключения производного класса никогда не сработает). Обработчик исключения Exception обрабатывает все возможные исключения и поэтому должен быть записан последним.

Пример.

var a: array of integer;

try

var i: integer;

readln(i);

writeln(a div i);

except

on System.DivideByZeroException do

writeln(‘Деление на 0’);

on e: System.IndexOutOfRangeException do

writeln(e.Message);

on System.FormatException do

writeln(‘Неверный формат ввода’);

else writeln(‘Какое-то другое исключение’);

end;

Оглавление книги

5.3. Warnings¶

The following exceptions are used as warning categories; see the
module for more information.

exception

Base class for warning categories.

exception

Base class for warnings generated by user code.

exception

Base class for warnings about deprecated features.

exception

Base class for warnings about features which will be deprecated in the future.

exception

Base class for warnings about dubious syntax.

exception

Base class for warnings about dubious runtime behavior.

exception

Base class for warnings about constructs that will change semantically in the
future.

exception

Base class for warnings about probable mistakes in module imports.

exception

Base class for warnings related to Unicode.

exception

Base class for warnings related to and .

Перехват исключений в Python

В Python исключения обрабатываются при помощи инструкции .

Критическая операция, которая может вызвать исключение, помещается внутрь блока . А код, при помощи которого это исключение будет обработано, — внутрь блока .

Таким образом, мы можем выбрать набор операций, который мы хотим совершить при перехвате исключения. Вот простой пример.

# Для получения типа исключения импортируем модуль sys
import sys

randomList = 

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!", sys.exc_info(), "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Результат:

В данном примере мы, при помощи цикла , производим итерацию списка . Как мы ранее заметили, часть кода, в которой может произойти ошибка, помещена внутри блока .

Если исключений не возникает, блок пропускается, а программа продолжает выполнятся обычным образом (в данном примере так происходит с последним элементом списка). Но если исключение появляется, оно сразу обрабатывается в блоке (в данном примере так происходит с первым и вторым элементом списка).

В нашем примере мы вывели на экран имя исключения при помощи функции , которую импортировали из модуля . Можно заметить, что элемент вызывает , а  вызывает .

Так как все исключения в Python наследуются из базового класса , мы можем переписать наш код следующим образом:

# Для получения типа исключения импортируем модуль sys
import sys

randomList = 

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Результат выполнения этого кода будет точно таким же.

Python try…finally

The statement in Python can have an optional clause. This clause is executed no matter what, and is generally used to release external resources.

For example, we may be connected to a remote data center through the network or working with a file or a Graphical User Interface (GUI).

In all these circumstances, we must clean up the resource before the program comes to a halt whether it successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are performed in the clause to guarantee the execution.

Here is an example of file operations to illustrate this.

This type of construct makes sure that the file is closed even if an exception occurs during the program execution.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector