Runtime error python что это
Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.
8.3. Handling Exceptions¶
It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control - C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.
The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:
A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:
Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.
All exceptions inherit from BaseException , and so it can be used to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):
Alternatively the last except clause may omit the exception name(s), however the exception value must then be retrieved from sys.exc_info()[1] .
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.
When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type.
The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args . For convenience, the exception instance defines __str__() so the arguments can be printed directly without having to reference .args . One may also instantiate an exception first before raising it and add any attributes to it as desired.
If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions.
Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:
Ошибка атрибута (AttributeError)
При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute .
8.5. Exception Chaining¶
The raise statement allows an optional from which enables chaining exceptions. For example:
This can be useful when you are transforming exceptions. For example:
Exception chaining happens automatically when an exception is raised inside an except or finally section. This can be disabled by using from None idiom:
For more information about chaining mechanics, see Built-in Exceptions .
Исключения
Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.
Ошибка прерывания с клавиатуры (KeyboardInterrupt)
Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.
В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt . Теперь обработаем исключение KeyboardInterrupt .
Ошибка утверждения (AssertionError)
Когда инструкция утверждения не верна, вызывается ошибка утверждения.
Рассмотрим пример. Предположим, есть две переменные: a и b . Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert , что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.
Ошибка отступа (IndentationError)
Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.
Ошибка рекурсии (RecursionError)
Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.
Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.
Чтобы воспроизвести эту ошибку, определим функцию recursion , которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.
8.6. User-defined Exceptions¶
Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.
Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.
Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.
Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter Classes .
Ошибка ключа
Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError .
Встроенные исключения
Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.
- Try : он запускает блок кода, в котором ожидается ошибка.
- Except : здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
- Else : если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
- Finally : вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.
В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.
Деление на ноль (ZeroDivisionError)
Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.
Ошибка индекса
Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).
Ошибка типа (TypeError)
8.8. Predefined Clean-up Actions¶
Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.
The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.
After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.
Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.
Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.
Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError , которые не стоит пытаться обработать.
Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.
Ошибки могут быть разных видов:
- Синтаксические
- Недостаточно памяти
- Ошибки рекурсии
- Исключения
Разберем их по очереди.
Арифметические ошибки (ArithmeticError)
- Ошибка деления на ноль (Zero Division);
- Ошибка переполнения (OverFlow);
- Ошибка плавающей точки (Floating Point);
Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.
2 Answers 2
A run time error is a type of error that is deliberately raised during program run time (hence the name). For example, in python, a runtime error can only occur when someone writes
This is meant to be a way to stop the program if there is a type of error that the program interpreter has not detected, but is capable of causing the program to not function as it has to. An example of when a runtime error is required is this function (a wrapper for the termcolor cprint function that takes a number as its color argument):
In this circumstance, the function will fail to run properly or inform the user of any kind of error if the color argument is not 1 or 2. The way to solve this, and make your program easier to use, is a runtime error (or larger libraries will create their own custom exceptions, this is not important). Basically, because an argument other than 1 or 2 is in fact an error in your program (that python won't catch and raise for you), it will raise an error for the user to diagnose. Here is the new and better version of the function:
Now, if the user makes a mistake, the program will catch this as an error, instead of failing to function or doing something unexpected, which would make it difficult to diagnose (and in some cases potentially vulnerable). This is why a runtime error is useful.
No matter your skill as a programmer, you will eventually make a coding mistake. Such mistakes come in three basic flavors:
- Syntax errors: Errors where the code is not valid Python (generally easy to fix)
- Runtime errors: Errors where syntactically valid code fails to execute, perhaps due to invalid user input (sometimes easy to fix)
- Semantic errors: Errors in logic: code executes without a problem, but the result is not what you expect (often very difficult to track-down and fix)
Here we're going to focus on how to deal cleanly with runtime errors. As we'll see, Python handles runtime errors via its exception handling framework.
Ошибка выполнения (Runtime Error)
Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented . Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.
Ошибка деления на ноль (ZeroDivisionError)
Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.
Теперь рассмотрим встроенные исключения Python.
Стандартные ошибки (StandardError)
Рассмотрим некоторые базовые ошибки в программировании.
Синтаксические ошибки (SyntaxError)
Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.
Рассмотрим на примере.
Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.
Catching Exceptions: try and except ¶
The main tool Python gives you for handling runtime exceptions is the try . except clause. Its basic structure is this:
Note that the second block here did not get executed: this is because the first block did not return an error. Let's put a problematic statement in the try block and see what happens:
Here we see that when the error was raised in the try statement (in this case, a ZeroDivisionError ), the error was caught, and the except statement was executed.
One way this is often used is to check user input within a function or another piece of code. For example, we might wish to have a function that catches zero-division and returns some other value, perhaps a suitably large number like $10^$:
There is a subtle problem with this code, though: what happens when another type of exception comes up? For example, this is probably not what we intended:
Dividing an integer and a string raises a TypeError , which our over-zealous code caught and assumed was a ZeroDivisionError ! For this reason, it's nearly always a better idea to catch exceptions explicitly:
Ошибка значения (ValueError)
Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.
В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.
8.4. Raising Exceptions¶
The raise statement allows the programmer to force a specified exception to occur. For example:
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception ). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:
If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
Ошибка памяти (MemoryError)
Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.
8.2. Exceptions¶
The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError , NameError and TypeError . The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).
The rest of the line provides detail based on the type of exception and what caused it.
The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.
Built-in Exceptions lists the built-in exceptions and their meanings.
8.7. Defining Clean-up Actions¶
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:
If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.
If the finally clause executes a break , continue or return statement, exceptions are not re-raised.
If the try statement reaches a break , continue or return statement, the finally clause will execute just prior to the break , continue or return statement’s execution.
If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.
A more complicated example:
As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.
In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
Runtime Errors¶
If you've done any coding in Python, you've likely come across runtime errors. They can happen in a lot of ways.
For example, if you try to reference an undefined variable:
Or if you try an operation that's not defined:
Or you might be trying to compute a mathematically ill-defined result:
Or maybe you're trying to access a sequence element that doesn't exist:
Note that in each case, Python is kind enough to not simply indicate that an error happened, but to spit out a meaningful exception that includes information about what exactly went wrong, along with the exact line of code where the error happened. Having access to meaningful errors like this is immensely useful when trying to trace the root of problems in your code.
Пользовательские исключения в Python
Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.
В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.
Недостаточно памяти (OutofMemoryError)
Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” ( heap ). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory . Она может появиться по нескольким причинам:
- Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
- Загрузка файла большого размера;
- Запуск модели машинного обучения/глубокого обучения и много другое;
Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError , позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.
Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc() ), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.
Ошибка импорта (ModuleNotFoundError)
Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.
Недостатки обработки исключений в Python
У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.
Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2 — if . Затем они выполняются 10000 раз с переменной a=0 . Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2 , который просто проверяет значение и не делает ничего, если условие не выполнено.
Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.
Ошибка имени (NameError)
Ошибка имени возникает, когда локальное или глобальное имя не находится.
В следующем примере переменная ans не определена. Результатом будет ошибка NameError .
Выводы!
Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.
Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.
Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.
Набрел на занятную статью о частых ошибках на Python у начинающих программистов. Мне кажется, она полезна будет для тех, кто перешел с другого языка или только планирует переход. Далее идет перевод.
1) Пропущено двоеточие в конце строки после управляющих конструкций типа if , elif , else , for , while , class , or def , что приведет к ошибке типа SyntaxError: invalid syntax
2) Использование = вместо == приводит к ошибке типа SyntaxError: invalid syntax
Символ = является оператором присваивания, а символ == — оператором сравнения.
Эта ошибка возникает в следующем коде:
3) Использование неправильного количества отступов.
Возникнет ошибка типа IndentationError: unexpected indent , IndentationError: unindent does not match any outer indentation level и IndentationError: expected an indented block
Нужно помнить, что отступ необходимо делать только после : , а по завершению блока обязательно вернуться к прежнему количеству отступов.
4) Неиспользование функции len() в объявлении цикла for для списков list
Возникнет ошибка типа TypeError: ‘list’ object cannot be interpreted as an integer
Часто возникает желание пройти в цикле по индексам элементов списка или строки, при этом требуется использовать функцию range() . Нужно помнить, что необходимо получить значение len(someList) вместо самого значения someList
Ошибка возникнет в следующем коде:
От переводчика: Иногда можно ошибочно перепутать метод shape с len() для определения размера списка. При этом возникает ошибка типа ‘list’ object has no attribute ‘shape’
5) Попытка изменить часть строки. (Ошибка типа TypeError: ‘str’ object does not support item assignment )
Строки имеют неизменяемый тип. Эта ошибка произойдет в следующем коде:
А ожидается такое результат:
От переводчика: Подробней про неизменяемость строк можно прочитать тут
6) Попытка соединить нестроковую переменную со строкой приведет к ошибке TypeError: Can’t convert ‘int’ object to str implicitly
Такая ошибка произойдет тут:
От переводчика: еще удобно так
7) Пропущена одинарная кавычка в начале или конце строковой переменной (Ошибка SyntaxError: EOL while scanning string literal )
Такая ошибка произойдет в следующем коде:
8) Опечатка в названии переменной или функции (Ошибка типа NameError: name ‘fooba’ is not defined )
Такая ошибка может встретиться в таком коде:
От переводчика: очень часто при написании возникают ошибки типа NameError: name ‘true’ is not defined и NameError: name ‘false’ is not defined , связанные с тем, что нужно писать булевные значения с большой буквы True и False
9) Ошибка при обращении к методу объекта. (Ошибка типа AttributeError: ‘str’ object has no attribute ‘lowerr’ )
Такая ошибка произойдет в следующем коде:
10) Попытка использовать индекс вне границ списка. (Ошибка типа IndexError: list index out of range )
Ошибка возникает в следующем коде:
11) Использование несуществующих ключей для словаря. (Ошибка типа KeyError: ‘spam’ )
Ошибка произойдет в следующем коде:
12) Использование зарезервированных в питоне ключевых слов в качестве имени для переменной. (Ошибка типа SyntaxError: invalid syntax )
Ключевые слова (зарезервированные) в питоне невозможно использовать как переменные. Пример в следующем коде:
Python 3 имеет следующие ключевые слова: and , as , assert , break , class , continue , def , del , elif , else , except , False , finally , for , from , global , if , import , in , is , lambda , None , nonlocal , not , or , pass , raise , return , True , try , while , with , yield
13) Использование операторов присваивания для новой неинициализированной переменной. (Ошибка типа NameError: name ‘foobar’ is not defined )
Не стоит надеяться, что переменные инициализируются при старте каким-нибудь значением типа 0 или пустой строкой.
Эта ошибка встречается в следующем коде:
Операторы присваивания типа spam += 1 эквивалентны spam = spam + 1 . Это означает, что переменная spam уже должна иметь какое-то значение до.
14) Использование локальных переменных, совпадающих по названию с глобальными переменными, в функции до инициализации локальной переменной. (Ошибка типа UnboundLocalError: local variable ‘foobar’ referenced before assignment )
Использование локальной переменной в функции с именем, совпадающим с глобальной переменной, опасно. Правило: если переменная в функции использовалась с оператором присвоения, это всегда локальная переменная для этой функции. В противном случае, это глобальная переменная внутри функции.
Это означает, что нельзя использовать глобальную переменную (с одинаковым именем как у локальной переменной) в функции до ее определения.
I made a game with Python 2.6. I also made it into an executable with cx_Freeze 4.3. When I run the executable on my computer it came up with this:
I don't understand what happened here. I tried solving the problem but with no luck. Then I searched the runtime error on google and it said it might be the compatibility. I wrote the original script on windows vista with the downloaded version of the windows 7 python 2.6. I did this because the windows vista had no internet so I downloaded the python, pygame and cx_freeze .msi files on my windows 7 laptop. Then I transferred the files to the desktop windows vista. Is this the problem? Or maybe the script? I don't think its the script as I can play the game when it is still a python script. Its a bit long though. I running windows 7 with python 2.6, pygame 2.6 and cx_freeze 4.3. Thanks if you can help me :).
Searching for pygame cx_freeze brings up many previous questions. Have you gone through them already?
Use search field (see top right corner on the page) to search cx_Freeze runtime and you get link to question Pygame Distribution - Runtime Error - maybe with answer to your problem
Ошибка поиска (LookupError)
LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.
Здесь есть два вида исключений:
- Ошибка индекса ( IndexError );
- Ошибка ключа ( KeyError );
8.1. Syntax Errors¶
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:
The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print() , since a colon ( ':' ) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.
Ошибка типа (TypeError)
Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.
В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.
Переполнение (OverflowError)
Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.
Читайте также: