Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.
Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.
Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError
, которые не стоит пытаться обработать.
Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.
Ошибки могут быть разных видов:
- Синтаксические
- Недостаточно памяти
- Ошибки рекурсии
- Исключения
Разберем их по очереди.
Синтаксические ошибки (SyntaxError)
Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.
Рассмотрим на примере.
a = 8
b = 10
c = a b
File "", line 3
c = a b
^
SyntaxError: invalid syntax
Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.
Недостаточно памяти (OutofMemoryError)
Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap
). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory
. Она может появиться по нескольким причинам:
- Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
- Загрузка файла большого размера;
- Запуск модели машинного обучения/глубокого обучения и много другое;
Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError
, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.
Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()
), не факт, что все процессы восстановятся — в некоторых случаях MemoryError
приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.
Ошибка рекурсии (RecursionError)
Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.
Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.
Чтобы воспроизвести эту ошибку, определим функцию recursion
, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow
или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.
def recursion():
return recursion()
recursion()
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
in
----> 1 recursion()
in recursion()
1 def recursion():
----> 2 return recursion()
... last 1 frames repeated, from the frame below ...
in recursion()
1 def recursion():
----> 2 return recursion()
RecursionError: maximum recursion depth exceeded
Ошибка отступа (IndentationError)
Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.
Пример:
for i in range(10):
print('Привет Мир!')
File "", line 2
print('Привет Мир!')
^
IndentationError: expected an indented block
Исключения
Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.
Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:
Ошибка типа (TypeError)
a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
1 a = 2
2 b = 'PythonRu'
----> 3 a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Ошибка деления на ноль (ZeroDivisionError)
10 / 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
in
----> 1 10 / 0
ZeroDivisionError: division by zero
Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError
и ZeroDivisionError
. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.
Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.
Теперь рассмотрим встроенные исключения Python.
Встроенные исключения
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
Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.
Try
: он запускает блок кода, в котором ожидается ошибка.Except
: здесь определяется тип исключения, который ожидается в блокеtry
(встроенный или созданный).Else
: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).Finally
: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.
В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.
Ошибка прерывания с клавиатуры (KeyboardInterrupt)
Исключение KeyboardInterrupt
вызывается при попытке остановить программу с помощью сочетания Ctrl + C
или Ctrl + Z
в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.
В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt
. Теперь обработаем исключение KeyboardInterrupt
.
try:
inp = input()
print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
print('Исключение KeyboardInterrupt')
else:
print('Исключений не произошло')
Исключение KeyboardInterrupt
Стандартные ошибки (StandardError)
Рассмотрим некоторые базовые ошибки в программировании.
Арифметические ошибки (ArithmeticError)
- Ошибка деления на ноль (Zero Division);
- Ошибка переполнения (OverFlow);
- Ошибка плавающей точки (Floating Point);
Все перечисленные выше исключения относятся к классу Arithmetic
и вызываются при ошибках в арифметических операциях.
Деление на ноль (ZeroDivisionError)
Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.
try:
a = 100 / 0
print(a)
except ZeroDivisionError:
print("Исключение ZeroDivisionError." )
else:
print("Успех, нет ошибок!")
Исключение ZeroDivisionError.
Переполнение (OverflowError)
Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.
try:
import math
print(math.exp(1000))
except OverflowError:
print("Исключение OverFlow.")
else:
print("Успех, нет ошибок!")
Исключение OverFlow.
Ошибка утверждения (AssertionError)
Когда инструкция утверждения не верна, вызывается ошибка утверждения.
Рассмотрим пример. Предположим, есть две переменные: a
и b
. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert
, что приведет к вызову исключения Assertion
в том случае, если выражение будет ложным.
try:
a = 100
b = "PythonRu"
assert a == b
except AssertionError:
print("Исключение AssertionError.")
else:
print("Успех, нет ошибок!")
Исключение AssertionError.
Ошибка атрибута (AttributeError)
При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes
нет атрибута с именем attribute
.
class Attributes(obj):
a = 2
print(a)
try:
obj = Attributes()
print(obj.attribute)
except AttributeError:
print("Исключение AttributeError.")
2
Исключение AttributeError.
Ошибка импорта (ModuleNotFoundError)
Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.
import nibabel
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
in
----> 1 import nibabel
ModuleNotFoundError: No module named 'nibabel'
Ошибка поиска (LookupError)
LockupError
выступает базовым классом для исключений, которые происходят, когда key
или index
используются для связывания или последовательность списка/словаря неверна или не существует.
Здесь есть два вида исключений:
- Ошибка индекса (
IndexError
); - Ошибка ключа (
KeyError
);
Ошибка ключа
Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError
.
try:
a = {1:'a', 2:'b', 3:'c'}
print(a[4])
except LookupError:
print("Исключение KeyError.")
else:
print("Успех, нет ошибок!")
Исключение KeyError.
Ошибка индекса
Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).
try:
a = ['a', 'b', 'c']
print(a[4])
except LookupError:
print("Исключение IndexError, индекс списка вне диапазона.")
else:
print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.
Ошибка памяти (MemoryError)
Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.
Ошибка имени (NameError)
Ошибка имени возникает, когда локальное или глобальное имя не находится.
В следующем примере переменная ans
не определена. Результатом будет ошибка NameError
.
try:
print(ans)
except NameError:
print("NameError: переменная 'ans' не определена")
else:
print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена
Ошибка выполнения (Runtime Error)
Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented
. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.
class BaseClass(object):
"""Опередляем класс"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
# функция ничего не делает
raise NotImplementedError(self.__class__.__name__ + '.do_something')
class SubClass(BaseClass):
"""Реализует функцию"""
def do_something(self):
# действительно что-то делает
print(self.__class__.__name__ + ' что-то делает!')
SubClass().do_something()
BaseClass().do_something()
SubClass что-то делает!
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
in
14
15 SubClass().do_something()
---> 16 BaseClass().do_something()
in do_something(self)
5 def do_something(self):
6 # функция ничего не делает
----> 7 raise NotImplementedError(self.__class__.__name__ + '.do_something')
8
9 class SubClass(BaseClass):
NotImplementedError: BaseClass.do_something
Ошибка типа (TypeError)
Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.
В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.
try:
a = 5
b = "PythonRu"
c = a + b
except TypeError:
print('Исключение TypeError')
else:
print('Успех, нет ошибок!')
Исключение TypeError
Ошибка значения (ValueError)
Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.
В этом примере встроенная операция float
получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.
try:
print(float('PythonRu'))
except ValueError:
print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'
Пользовательские исключения в Python
В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.
Это можно сделать, создав новый класс, который будет наследовать из класса Exception
в Python.
class UnAcceptedValueError(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
Total_Marks = int(input("Введите общее количество баллов: "))
try:
Num_of_Sections = int(input("Введите количество разделов: "))
if(Num_of_Sections < 1):
raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
print("Полученная ошибка:", e.data)
Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1
В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.
Недостатки обработки исключений в Python
У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.
Дальше пример, где модуль Python timeit
используется для проверки времени исполнения 2 разных инструкций. В stmt1
для обработки ZeroDivisionError
используется try-except, а в stmt2
— if
. Затем они выполняются 10000 раз с переменной a=0
. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1
с обработкой исключений занимает больше времени чем stmt2
, который просто проверяет значение и не делает ничего, если условие не выполнено.
Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.
import timeit
setup="a=0"
stmt1 = '''
try:
b=10/a
except ZeroDivisionError:
pass'''
stmt2 = '''
if a!=0:
b=10/a'''
print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))
time= 0.003897680000136461
time= 0.0002797570000439009
Выводы!
Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.
Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try
выискивает исключения, а except
их обрабатывает.
Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.
Have you ever tried to divide an integer with a string while programming in Python? If yes, you might have got an error message like “TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’”. In this article, we will discuss this TypeError exception in Python. We will also look at different situations when a TypeError exception can occur and how we can avoid them.
Table of Contents
- What is TypeError in Python?
- When does a TypeError Exception Occur in Python?
- TypeError Exceptions May Occur While Using In-Built Functions
- TypeError Exceptions May Occur While Performing Operations Between Two Incompatible Data Types
- TypeError Exceptions May Occur While Calling a Non-callable Object
- How to Avoid TypeError Exceptions in Python?
- Conclusion
What is TypeError in Python?
TypeError is an exception in Python programming language that occurs when the data type of objects in an operation is inappropriate. For example, If you attempt to divide an integer with a string, the data types of the integer and the string object will not be compatible. Due to this, the Python interpreter will raise a TypeError exception as shown in the following example.
myInt = 100
myStr = "10"
myResult = myInt / myStr
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = myInt / myStr
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Let us take another example, Suppose that we want to concatenate two lists. We can do it using the + operator as follows.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
myResult = list1 + list2
print("First list is:", list1)
print("second list is:", list2)
print("Resultant list is:", myResult)
Output:
First list is: [1, 2, 3]
second list is: [4, 5, 6]
Resultant list is: [1, 2, 3, 4, 5, 6]
Now suppose that we pass a tuple in the place of the second list. Here, list and tuple data types are incompatible with each other in a concatenation operator. So, the python interpreter will raise a TypeError exception as shown below.
list1 = [1, 2, 3]
list2 = (4, 5, 6)
myResult = list1 + list2
print("First list is:", list1)
print("second list is:", list2)
print("Resultant list is:", myResult)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = list1 + list2
TypeError: can only concatenate list (not "tuple") to list
Looking at these examples, we can say that TypeError is an exception that is raised by the python interpreter if the data types of different objects in an operation are not compatible and hence inappropriate.
Let us now look at some situations where TypeError exceptions are likely to occur.
When does a TypeError Exception Occur in Python?
Exceptions force the program to terminate prematurely. Also, no one wants exceptions to occur in their programs. But, we cannot control how a user will pass inputs to the program. There can be various situations where TypeError exceptions can occur.
Let’s have a look at some of them.
TypeError Exceptions May Occur While Using In-Built Functions
All the built-in functions accept input arguments of certain types. For example, the add() method in a set accepts only immutable objects like integers, strings, tuples, floating point numbers, etc as input arguments. If we try to give a mutable object like a list as input to the add() method, it will raise TypeError with a message “TypeError: unhashable type: ‘list’ ” as follows.
mySet = {1, 2, 3}
myList = [4, 5, 6]
mySet.add(myList)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
mySet.add(myList)
TypeError: unhashable type: 'list'
TypeError Exceptions May Occur While Performing Operations Between Two Incompatible Data Types
We know that mathematical or bitwise operations are defined only for certain data types in Python. For example, We can add an integer to an integer or a floating-point number. On the other hand, We cannot add a string object to an integer. Adding an integer to a string object will cause TypeError with the message “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’” as follows.
myInt = 100
myStr = "200"
myResult = myInt + myStr
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = myInt + myStr
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Likewise, all the mathematical operations are allowed only between certain data types. If you try to perform a mathematical operation on objects with incompatible data types, TypeError will occur.
If we talk about bitwise operations, we can perform a bitwise operation on an integer but not on a string. For example, we can right-shift an integer by two bits as follows.
myInt = 100
myResult = myInt >> 2
print("The given Integer is:", myInt)
print("Result is:", myResult)
Output:
The given Integer is: 100
Result is: 25
On the other hand, if we try to perform a right shift operation on a string, it will raise TypeError with the message “TypeError: unsupported operand type(s) for >>: ‘str’ and ‘int’ ” as follows.
myStr = "100"
myResult = myStr >> 2
print("The given String is:", myStr)
print("Result is:", myResult)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
myResult = myStr >> 2
TypeError: unsupported operand type(s) for >>: 'str' and 'int'
So, you can see that performing mathematical or bitwise operations on incompatible data types can cause a TypeError exception in your program.
TypeError Exceptions May Occur While Calling a Non-callable Object
In python, functions, methods, and all the objects with the implementation of __call__() method in their class definition are callable. We can call any callable object as we call a function or a method.
On the other hand, if we call a non-callable object such as an integer, it will raise a TypeError exception with the message “TypeError: ‘int’ object is not callable” as follows.
myInt = 100
myInt()
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
myInt()
TypeError: 'int' object is not callable
How to Avoid TypeError Exceptions in Python?
Errors are inevitable in a program. But, you can always minimize the occurrence of errors. To minimize TypeError exceptions you can use the following guidelines.
- Whenever you are trying to use an in-built method or function, always read its documentation. This will help you understand the inputs and outputs of the functions. Knowledge of the inputs and outputs will help you avoid TypeError exceptions in your program.
- While performing mathematical or bitwise operations, you can check the data types of the operands beforehand. This will help you avoid performing mathematical or bitwise operations on incompatible data types. Hence, you will be able to avoid TypeError exceptions.
- Give proper names to variables, functions, classes, and methods in your programs. This will help you avoid calling a non-callable object. Hence, you will be able to avoid TypeError exceptions.
Conclusion
In this article, we have discussed the TypeError exception, its causes, and how we can avoid them. You can also handle these exceptions using python try-except blocks. But, I will advise you to avoid the exception instead of handling it after it has occurred.
To learn more about python programming, you can read this article on string manipulation in Python. You might also like this article on Python IndexError.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.
Examples
The general causes for TypeError being raised are:
1. Unsupported operation between two types:
In the following example, the variable ‘geek’ is a string and the variable ‘num’ is an integer. The + (addition) operator cannot be used between these two types and hence TypeError is raised.
Python3
geek
=
"Geeks"
num
=
4
print
(geek
+
num
+
geek)
Output :
TypeError: must be str, not int
2. Calling a non-callable identifier:
In the below example code, the variable ‘geek’ is a string and is non-callable in this context. Since it is called in the print statement, TypeError is raised.
Python3
geek
=
"GeeksforGeeks"
print
(geek())
Output :
TypeError: 'str' object is not callable
3. Incorrect type of list index:
In Python, list indices must always be an integer value. Since the index value used in the following code is a string, it raises TypeError.
Python3
geeky_list
=
[
"geek"
,
"GeeksforGeeks"
,
"geeky"
,
"geekgod"
]
index
=
"1"
print
(geeky_list[index])
Output :
TypeError: list indices must be integers or slices, not str
4. Iterating through a non-iterative identifier:
In the following code, the value 1234.567890 is a floating-point number and hence it is non-iterative. Forcing Python to iterate on a non-iterative identifier will raise TypeError.
Python3
for
geek
in
1234.567890
:
print
(geek)
Output :
TypeError: 'float' object is not iterable
Handling TypeError
TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block. In the following example, when one of the indices is found to be an incorrect type, an exception is raised and handled by the program.
Python3
geeky_list
=
[
"Geeky"
,
"GeeksforGeeks"
,
"SuperGeek"
,
"Geek"
]
indices
=
[
0
,
1
,
"2"
,
3
]
for
i
in
range
(
len
(indices)):
try
:
print
(geeky_list[indices[i]])
except
TypeError:
print
(
"TypeError: Check list of indices"
)
Output :
Geeky GeeksforGeeks TypeError: Check list of indices Geek
Last Updated :
20 Aug, 2020
Like Article
Save Article
The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage.
Such an error is called a syntax error. The Python interpreter immediately reports it, usually along with the reason.
>>> print "hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?
In Python 3.x, print is a built-in function and requires parentheses. The statement above violates this usage and hence syntax error is displayed.
Many times though, a program results in an error after it is run even if it doesn’t have any syntax error. Such an error is a runtime error, called an exception.
A number of built-in exceptions are defined in the Python library.
Let’s see some common error types.
The following table lists important built-in exceptions in Python.
Exception | Description |
---|---|
AssertionError | Raised when the assert statement fails. |
AttributeError | Raised on the attribute assignment or reference fails. |
EOFError | Raised when the input() function hits the end-of-file condition. |
FloatingPointError | Raised when a floating point operation fails. |
GeneratorExit | Raised when a generator’s close() method is called. |
ImportError | Raised when the imported module is not found. |
IndexError | Raised when the index of a sequence is out of range. |
KeyError | Raised when a key is not found in a dictionary. |
KeyboardInterrupt | Raised when the user hits the interrupt key (Ctrl+c or delete). |
MemoryError | Raised when an operation runs out of memory. |
NameError | Raised when a variable is not found in the local or global scope. |
NotImplementedError | Raised by abstract methods. |
OSError | Raised when a system operation causes a system-related error. |
OverflowError | Raised when the result of an arithmetic operation is too large to be represented. |
ReferenceError | Raised when a weak reference proxy is used to access a garbage collected referent. |
RuntimeError | Raised when an error does not fall under any other category. |
StopIteration | Raised by the next() function to indicate that there is no further item to be returned by the iterator. |
SyntaxError | Raised by the parser when a syntax error is encountered. |
IndentationError | Raised when there is an incorrect indentation. |
TabError | Raised when the indentation consists of inconsistent tabs and spaces. |
SystemError | Raised when the interpreter detects internal error. |
SystemExit | Raised by the sys.exit() function. |
TypeError | Raised when a function or operation is applied to an object of an incorrect type. |
UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
UnicodeError | Raised when a Unicode-related encoding or decoding error occurs. |
UnicodeEncodeError | Raised when a Unicode-related error occurs during encoding. |
UnicodeDecodeError | Raised when a Unicode-related error occurs during decoding. |
UnicodeTranslateError | Raised when a Unicode-related error occurs during translation. |
ValueError | Raised when a function gets an argument of correct type but improper value. |
ZeroDivisionError | Raised when the second operand of a division or module operation is zero. |
IndexError
The IndexError
is thrown when trying to access an item at an invalid index.
>>> L1=[1,2,3]
>>> L1[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
L1[3]
IndexError: list index out of range
ModuleNotFoundError
The ModuleNotFoundError
is thrown when a module could not be found.
>>> import notamodule
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
import notamodule
ModuleNotFoundError: No module named 'notamodule'
KeyError
The KeyError
is thrown when a key is not found.
>>> D1={'1':"aa", '2':"bb", '3':"cc"}
>>> D1['4']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
D1['4']
KeyError: '4'
ImportError
The ImportError
is thrown when a specified function can not be found.
>>> from math import cube
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
from math import cube
ImportError: cannot import name 'cube'
StopIteration
The StopIteration
is thrown when the next()
function goes beyond the iterator items.
>>> it=iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
next(it)
StopIteration
TypeError
The TypeError
is thrown when an operation or function is applied to an object of an inappropriate type.
>>> '2'+2
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
'2'+2
TypeError: must be str, not int
ValueError
The ValueError
is thrown when a function’s argument is of an inappropriate type.
>>> int('xyz')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
int('xyz')
ValueError: invalid literal for int() with base 10: 'xyz'
NameError
The NameError
is thrown when an object could not be found.
>>> age
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
age
NameError: name 'age' is not defined
ZeroDivisionError
The ZeroDivisionError
is thrown when the second operator in the division is zero.
>>> x=100/0
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x=100/0
ZeroDivisionError: division by zero
KeyboardInterrupt
The KeyboardInterrupt
is thrown when the user hits the interrupt key (normally Control-C) during the execution of the program.
>>> name=input('enter your name')
enter your name^c
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
name=input('enter your name')
KeyboardInterrupt
Learn how to handle exceptions in Python in the next chapter.
Ситуация: начинающий программист более-менее освоил JavaScript и перешёл к Python. Чтобы освоить новый язык на практике, программист решил переписать свой старый проект с JavaScript на Python и столкнулся с таким фрагментом:
var a = 2;
var b = ' ствола';
var c = a + b;
Программист помнит, что в Python для переменных не нужен var, а можно просто объявлять их в нужном месте, поэтому он написал такой код:
a = 2
b = ‘ ствола’
c = a + b
Но при запуске проекта компьютер указал на последнюю строку и выдал ошибку:
Exception has occurred: TypeError
unsupported operand type(s) for +: ‘int’ and ‘str’
Почему так происходит: в JavaScript есть автоматическое приведение типов, и компьютер берёт на себя перевод данных из одного типа в другой. В нашем примере он сделает так:
- Возьмёт число и строку.
- Увидит, что их нужно сложить.
- Посмотрит по своим правилам, к какому одному типу проще всего привести всё в этой ситуации.
- Поймёт, что проще перевести число в строку, чем наоборот.
- Сделает так и на выходе получит строку «2 ствола»
Но Python так не умеет — ему нужно, чтобы данные были одного типа или хотя бы из одного семейства: оба числовые, оба строковые и так далее. Так как сейчас идёт сложение разных типов данных, то Питон говорит, что он так делать не будет, и падает с ошибкой.
Что делать с ошибкой Exception has occurred: TypeError
Чтобы исправить эту ошибку, нужно вручную привести данные к одному типу или явно указать их при операции.
В нашем случае можно сделать так: при сложении сказать компьютеру напрямую, что мы хотим в сложении использовать переменную a как строку:
a = 2
b = ‘ ствола’
c = str(a) + b
Команда str() не меняет тип и содержимое переменной a, но зато компьютер понимает, что это временно стало строкой, и спокойно её складывает со второй строкой.