Ошибка an exception occurred type

Ситуация: начинающий программист более-менее освоил 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 есть автоматическое приведение типов, и компьютер берёт на себя перевод данных из одного типа в другой. В нашем примере он сделает так:

  1. Возьмёт число и строку.
  2. Увидит, что их нужно сложить.
  3. Посмотрит по своим правилам, к какому одному типу проще всего привести всё в этой ситуации. 
  4. Поймёт, что проще перевести число в строку, чем наоборот.
  5. Сделает так и на выходе получит строку «2 ствола»

Но Python так не умеет — ему нужно, чтобы данные были одного типа или хотя бы из одного семейства: оба числовые, оба строковые и так далее. Так как сейчас идёт сложение разных типов данных, то Питон говорит, что он так делать не будет, и падает с ошибкой.

Что делать с ошибкой Exception has occurred: TypeError

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

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

a = 2
b = ‘ ствола’
c = str(a) + b

Команда str() не меняет тип и содержимое переменной a, но зато компьютер понимает, что это временно стало строкой, и спокойно её складывает со второй строкой.

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

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

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в 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, а в stmt2if. Затем они выполняются 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 их обрабатывает.

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

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

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

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

  1. What is TypeError in Python?
  2. When does a TypeError Exception Occur in Python?
    1. TypeError Exceptions May Occur While Using In-Built Functions
    2. TypeError Exceptions May Occur While Performing Operations Between Two Incompatible Data Types
    3. TypeError Exceptions May Occur While Calling a Non-callable Object
  3. How to Avoid TypeError Exceptions in Python?
  4. 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.

  1. 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.
  2. 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.
  3. 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.

Python TypeError

Introduction to Python TypeError

TypeError is a kind of error that python generates. We are trying to perform the operation of the wrong type of object. For example, if we are trying to do the square root of a number but we are passing a list instead of int, then TypeError will be generated by the python. This type of error is also generated when we are trying to perform the operation on the object, and it is not supported.

How to Avoid TypeError?

Python always checks the type of object we are passing for operation and whether a particular object type supports the operation. Python will throw a TypeError. We can avoid this error by adding an extra step or try-catch before such an operation. Suppose we want to join two lists. So before joining the operation, we can check the type of both the list that the user passes; if the type doesn’t match our requirement, we can pass a message to the user indicating wrong input and tell him to pass the proper input.

Examples of Python TypeError

Following are the examples are given below:

Example #1

Code:

list1 = [7,8,9,10]
list2 = 's';
result = list2.join(list1)
print(result)

Output:

Python TypeError-1.1

As you can see in the above program, we have created a list of list1 and list2 as a string variable. Now we are trying to join the list1 with list2, but python returns the type error. Because list2 is of string type, and python is expecting each element of the list1 to be a string, but it’s an integer.

Example #2

Code:

list1 = ['7','8',9,10]
list2 = 's';
result = list2.join(list1)
print(result)

Output:

Python TypeError-1.2

Now in the above, we have modified our first list, we have made the first two elements as a string, but the rest two elements are still int. So when we execute it, python still generates TypeError, as it says element index 2, i.e. the third element is still an integer. So now we have to make the rest two elements also as integers to work properly.

Example #3

Code:

list1 = ['7','8',9,10]
list2 = 's';
result = list2.join(str(a) for a in list1)
print(result)

Output:

Python TypeError-1.3

In the above program, you can see inside the join function, we have converted each element of list1 into a string by typecasting. It will make sure each element is a string; if not, then it will be covert it. So in this way, we can avoid TypeError.

Example #4

Code:

a = 's';
b = 4;
c = a/b;
print(c)

Output:

Python TypeError-1.4

In the above example, you can see that we have created two variables. One is holding an integer value, and another is holding a string or character value. Now we are trying to perform division between the variable and hold the result into the third variable and printing the result. But python will throw TypeError because an integer cannot be divided by string or character, the python was expecting integer value, so it throws TypeError.

Now in such cases, we know that we have to do division operation, and both variables should be an integer, so we have to handle it before performing such an operation.

Example #5

Code:

a = 's';
b = 4;

if(type(b) != int or type(a) != int):
    print('One of the number is not integer')
else:
    c = a/b;
    print(c)

Output:

Output-1.5

In this example, we can see that we have put the if condition checking the type of both the variables; if any of the variables is not an integer, then we are passing a message to the user to enter the values again. In this way, we can avoid TypeError.

Code:

a = 5;
b = 4;

if(type(b) != int or type(a) != int):
    print('One of the number is not integer')
else:
    c = a/b;
    print(c)

Output:

Output-1.6

This time our program worked correctly.

Example #6

Code:

list1 = 's';
list2 = [3, 4, 5, 8, 9];
print(list1 + list2)

Output:

Output-1.7

In the above example, you can; we are trying to contact two variables. One is a holding string, and the other is a holding list. Python returns a type error because the string cannot be concatenated to the list. Python is expecting a list, so it returns a type error. So to avoid this, we can check the type of variable before executing the operation.

Code:

list1 = 's';
list2 = [3, 4, 5, 8, 9];

if(type(list1) != list or type(list2) != list):
    print('One of the values is not list')
else:
    print(list1 + list2)

Output:

Output-1.8

In this example, we are checking the type of both the variables before contacting them; thus, we can avoid this type of error.

Recommended Articles

This is a guide to Python TypeError. Here we also discuss the introduction and how to avoid typeerror? Along with different examples and its code implementation. you may also have a look at the following articles to learn more –

  1. Python Constants
  2. Quick Sort in Python
  3. Python Concurrency
  4. Python argparse

30 Days Of Python: Day 15 — Python Type Errors

Twitter Follow

Author:
Asabeneh Yetayeh
Second Edition: July, 2021

<< Day 14 | Day 16 >>

30DaysOfPython

  • 📘 Day 15
    • Python Error Types
      • SyntaxError
      • NameError
      • IndexError
      • ModuleNotFoundError
      • AttributeError
      • KeyError
      • TypeError
      • ImportError
      • ValueError
      • ZeroDivisionError
    • 💻 Exercises: Day 15

📘 Day 15

Python Error Types

When we write code it is common that we make a typo or some other common error. If our code fails to run, the Python interpreter will display a message, containing feedback with information on where the problem occurs and the type of an error. It will also sometimes gives us suggestions on a possible fix. Understanding different types of errors in programming languages will help us to debug our code quickly and also it makes us better at what we do.

Let us see the most common error types one by one. First let us open our Python interactive shell. Go to your you computer terminal and write ‘python’. The python interactive shell will be opened.

SyntaxError

Example 1: SyntaxError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
  File "<stdin>", line 1
    print 'hello world'
                      ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
>>>

As you can see we made a syntax error because we forgot to enclose the string with parenthesis and Python already suggests the solution. Let us fix it.

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
  File "<stdin>", line 1
    print 'hello world'
                      ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
>>> print('hello world')
hello world
>>>

The error was a SyntaxError. After the fix our code was executed without a hitch. Let see more error types.

NameError

Example 1: NameError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
>>>

As you can see from the message above, name age is not defined. Yes, it is true that we did not define an age variable but we were trying to print it out as if we had had declared it. Now, lets fix this by declaring it and assigning with a value.

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
>>> age = 25
>>> print(age)
25
>>>

The type of error was a NameError. We debugged the error by defining the variable name.

IndexError

Example 1: IndexError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

In the example above, Python raised an IndexError, because the list has only indexes from 0 to 4 , so it was out of range.

ModuleNotFoundError

Example 1: ModuleNotFoundError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>>

In the example above, I added an extra s to math deliberately and ModuleNotFoundError was raised. Lets fix it by removing the extra s from math.

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>>

We fixed it, so let’s use some of the functions from the math module.

AttributeError

Example 1: AttributeError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>> math.PI
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'math' has no attribute 'PI'
>>>

As you can see, I made a mistake again! Instead of pi, I tried to call a PI function from maths module. It raised an attribute error, it means, that the function does not exist in the module. Lets fix it by changing from PI to pi.

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>> math.PI
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'math' has no attribute 'PI'
>>> math.pi
3.141592653589793
>>>

Now, when we call pi from the math module we got the result.

KeyError

Example 1: KeyError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> users = {'name':'Asab', 'age':250, 'country':'Finland'}
>>> users['name']
'Asab'
>>> users['county']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'county'
>>>

As you can see, there was a typo in the key used to get the dictionary value. so, this is a key error and the fix is quite straight forward. Let’s do this!

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user = {'name':'Asab', 'age':250, 'country':'Finland'}
>>> user['name']
'Asab'
>>> user['county']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'county'
>>> user['country']
'Finland'
>>>

We debugged the error, our code ran and we got the value.

TypeError

Example 1: TypeError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

In the example above, a TypeError is raised because we cannot add a number to a string. First solution would be to convert the string to int or float. Another solution would be converting the number to a string (the result then would be ’43’). Let us follow the first fix.

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 4 + int('3')
7
>>> 4 + float('3')
7.0
>>>

Error removed and we got the result we expected.

ImportError

Example 1: TypeError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'power' from 'math'
>>>

There is no function called power in the math module, it goes with a different name: pow. Let’s correct it:

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'power' from 'math'
>>> from math import pow
>>> pow(2,3)
8.0
>>>

ValueError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('12a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12a'
>>>

In this case we cannot change the given string to a number, because of the ‘a’ letter in it.

ZeroDivisionError

asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>

We cannot divide a number by zero.

We have covered some of the python error types, if you want to check more about it check the python documentation about python error types.
If you are good at reading the error types then you will be able to fix your bugs fast and you will also become a better programmer.

🌕 You are excelling. You made it to half way to your way to greatness. Now do some exercises for your brain and for your muscle.

💻 Exercises: Day 15

  1. Open you python interactive shell and try all the examples covered in this section.

🎉 CONGRATULATIONS ! 🎉

<< Day 14 | Day 16 >>

Ошибок не допускает только тот, кто ничего не делает и программирование не исключение. С ростом кода и объема разработки, также растет вероятность получить error в терминале. Именно по причине весовой вероятности появления ошибок исключения в python и других языках программирования — это обязательная часть.

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

В Python обработка исключений имеет колоссальное значение. Неполадки возможны как элементарные, так и скрытые в особенностях языка или логике построения. Если программист считает, что пользователь никогда не сделает ошибки – он их обязательно совершит. Идеального решения в программном коде не существует и существовать не может, следовательно, добавлять исключение и уметь их обрабатывать профессиональная необходимость.

Как устроен механизм исключений

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

На курсах python https://volgograd.videoforme.ru/computer-programming-school/python-for-beginners объясняют, что обработка ошибок происходит во многом за счет пойманного exceptions. Код, который потенциально может быть проломным, оборачивается в своего рода ловушку. Если проблем нет, то все проходит стандартно, но только появляться exceptions мы выходим из потенциально проблемного участка и идем по пути исключения. По сути данный механизм можно условно сравнить if – else, когда все хорошо мы в if, когда сломалось в else (при этом в else также прилетит exceptions).

Синтаксические ошибки (SyntaxError)

От ошибок в синтаксисе никто не застрахован. Конечно, значительно чаще этим грешат новички программирования. Возьмем пример:

.py

employee = [

['Иванов', 'бухгалтер'],

['Денисов', 'инженер'],

]

for employee_name, employee_post in employee:

label = 'Имя: { employee_name }. Должность: { employee_post }'.format(

employeу_name = employeу_name

employee_post = employee_post

)

print(label) # SyntaxError

Код кажется простым и понятным, но в нем скрыта едва заметная ошибка, которая не даст коду запуститься. Пример показывает, что простая запятая легко сломает программу. Естественно, в интерпретированной среде python выдает ошибку, особенно настолько элементарную. Ошибка SyntaxError иногда преследует программиста, когда меняют функции внутри библиотеки, или он просто утомился. В остальном это беда новичков, которые только знакомятся с языком и его синтаксисом.

Недостаточно памяти (OutofMemoryError)

Ошибки python вроде нехватки памяти далеко не редки, причин на то очень много. Разберём три основные:

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

Утечка данных – переменные в Питон ссылочного типа и в теории он их удаляет, как только они ему не нужны. Но вполне можно организовать ситуацию, когда данные не будут удаляться и постепенно забьют все свободную память.

Бесконечные циклы – когда условия выхода из цикла никогда не наступят, в какой-то момент выделяемая память просто закончиться.

Ошибка рекурсии (RecursionError)

Рекурсия сам по себе не самый безопасный подход, но благодаря ей можно значительно облегчить код. Типы ошибок python вроде RecursionError, по сути, это срабатывание защиты внутри самого языка. Программисту выходят предупреждения, что, вероятно, запустил бесконечную рекурсию и выделенные под предел достигнут.

Простой пример бесконечной рекурсии:

def recurs():

recurs()

recurs() # RecursionError

Ошибка отступа (IndentationError)

Виды ошибок в Питоне вроде неправильных отступов, опять же можно отнести к ошибкам новичков. В Python теле любого логического процесса обозначается четырьмя пробелами. Если есть «:», а внизу на том же уровне идет код — это явная ошибка.

Пример такой явной ошибки:

def spaceBar():

pass

spaceBar() # IndentationError

Типы исключений

Исключения позволяют застраховаться программисту от вероятных неисправностей. Более того, становиться возможным отладить и исправить программу на разных этапах разработки. Обработка исключений в Питон можно назвать фундаментальным навыком, необходимым для развития python разработчика.

Исключение берет свою основу от BaseException, базового исключения от которого наследуются все остальные, именно этот базовый класс позволяет создавать собственные исключения.

Наследуясь от базового класса, исключения делятся на:

  • SystemExit
  • KeyboardInterrupt
  • GeneratorExit
  • Exception

Exception единственное несистемное исключение, с которым работает программист. От этого класса идут следующие виды исключений.

Ошибка типа (TypeError)

Один из довольно распространённых типов ошибок проследить все цепочку наследования легко: BaseException, Exception, TypeError. Данное исключение сработает, когда указанный тип данных не существует.

Ошибка деления на ноль (ZeroDivisionError)

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

print( 0 / 0 ) # ZeroDivisionError

Встроенные исключения

Встроенные исключения – это виды ошибок в Питоне, условия исполнения которых четко прописаны в языке. Здесь можно вспомнить деление на ноль, отсутствие или лишние пробелы.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Системное исключение KeyboardInterrupt дает прерывание программы какой-то клавишей или сочетанием клавиш, по умолчанию используется Ctrl+C. Это удобный способ прервать, к примеру, бесконечный цикл, когда явно программа работает неправильно.

Как обрабатывать исключения в Python (try except)

Стандартно в Python 3-я обработка исключений строится на try – except, эта конструкция очень часто встречающийся в разных языках программирования. Код обработки исключения выглядит так:

try: # место кода, где возможно срабатывание исключения

a= 10 / 0 # Явная арифметическая ошибка попадает в исключение ZeroDivisionError

except ZeroDivisionError: # Попадаем в исключение сработал ZeroDivisionError

a = 10 / 2 # Операция без ошибок

print( a ) # 5.0 – при делении получаем вещественное число

As — сохраняет ошибку в переменную

В Python try except текст ошибки выводится не через класс, а через экземпляр класса. Для примера попробуем узнать, какая ошибка произошла в коде:

try:

a= 10 - '10'

except Exception:

a = Exception

print( a )

В теории мы ожидаем получить текс ошибки, но результат выполнения программы будет «». Знакомый с языком программирования человек сразу поймет, что он получил не ошибку, а ссылку на класс.

Нам необходимо создать экземпляр класса. Для этого в «except» добавляется «as». Попробуем через try except python вывести ошибку правильно:

try:

a= 10 - '10'

except Exception as Ex:

a = Ex

print( a ) # unsupported operand type(s) for -: 'int' and 'str'

Теперь мы получаем текст о сработавшем исключении с пояснением ошибки.

Finally — выполняется всегда

Finally в конструкции try – except работает так же, как, например, в более знакомом программистам if – else. Попробуем разобрать на примере:

try:

a= 10 - '1' # Явная ошибка вычитания из числа строки

# a= 10 – 1 # Пример без ошибки

except Exception as Ex:

a = Ex

finally: #Все ниже сработает при любом результате

if type (a) == int: #Если все нормально сработало и мы получили число

print( f'получен результат: {a}' )

else:

print( f'произошла ошибка: {a}' )

Блок finally выполнится при любом результате работы программы, сработало или не сработало исключение.

Else — выполняется, когда исключение не было вызвано

Если except python вывод ошибки, то else это обработка, когда ошибки не произошло. Попробуем придумать пример для демонстрации:

try:

a = 10 – 1

#a = 10 - '1' # если захотим проверить пример с ошибкой

except Exception as Ex:

a = Ex

else: # код сработает только, если никаких ошибок не было

a = a * 2
finally:

print( a )

Несколько блоков except

Чем сложнее программа, тем с большим количеством ошибок приходится встречаться. Базовый try except python 3 вывести ошибку не только одним блоком. Except может быть столько, сколько возможных исключений допустимо. Попробуем реализовать в программе:

try:

a = int( input( 'Введите число : ' ))

b = 100 / a

except ZeroDivisionError:

b = 'деление на ноль'

except ValueError:

b = 'ошибка несоответствия типов'

except Exception:

b = 'что-то пошло не так'

print( f'результат работы программы : {b}' )

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

Несколько типов исключений в одном блоке except

В целом исключения определённого типа вполне возможно группировать. Здесь нет жестких ограничений. Попробуем в python try except вывести текст ошибки на примере кода:

try:

a = int(input('Введите число : '))

b = 100 / a

except (ZeroDivisionError, ValueError):

b = 'Введено недопустимое значение'

except Exception:

b = 'что-то пошло не так'

print( результат работы программы : {b}' )

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

Raise — самостоятельный вызов исключений

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

try:

raise Exception("произошла ошибка")

except Exception as e:

print("В программе есть событие : " + str(e))

Встречаясь с raise функция или программа идет к ближайшему except Exception. Так можно не только обработать ошибку, но прописать в каком блоке кода ошибка произошла.

Как пропустить ошибку

Для программиста в python try except вывести текст ошибки важно, но не обязательно. Ошибку можно банально пропустить не пропустить без вреда для кода, рассмотрим пример:

a = 5

try:

a = a / 0

except Exception:

pass

print(a)

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

Стандартные ошибки (StandardError)

С большинством ошибок, существующих в Питоне, программист никогда не встретится, многие из них встречаются в реальных проектах слишком редко. Рассмотрим, какая в python 3 обработка ошибок часто встречается.

Арифметические ошибки (ArithmeticError)

Класс, предназначенный для обработки арифметических ошибок, от него наследуются три класса:

FloatingPointError

– неудачное выполнение операций с вещественными числами. На практике редко встречается.

OverflowErro

– результат математической операции — слишком большое число, обычно это вещественное число.

ZeroDivisionError

– операция приводит к делению на ноль.

Ошибка утверждения (AssertionError)

– класс ошибки, срабатывающий если работа функции assert возвращает ложное утверждение.

Ошибка атрибута (AttributeError)

– класс ошибок, происходящих с отсутствием атрибута функций или методов.

Ошибка импорта (ModuleNotFoundError)

– ошибка, говорящая об отсутствии установленного модуля или пакета

Ошибка поиска (LookupError)

– исключение, срабатывающее при обращении к ключу или индексу несуществующему у объекта.

Ошибка ключа

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

Ошибка индекса

– срабатывает когда указанный индекс в объекте типа словарь не существует.

Ошибка памяти (MemoryError)

– в python 3 обработка ошибок срабатывающее, когда памяти для работы программы не хватает или память переполнена.

Ошибка имени (NameError)

– связана с тем, что указываемое название переменой, класса или функции не существует.

Ошибка выполнения (Runtime Error)

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

Ошибка типа (TypeError)

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

Ошибка значения (ValueError)

– исключение чаше встречающееся во время невозможности преобразования типов данных.

Пользовательские исключения в Python

Программист может создать собственный вариант исключений, наследуясь от Exception. Тут стоит обдумывать причины срабатывания и как вывести ошибку python. Код будет выглядеть примерно так:

class MyException(Exception):

pass

try:

val = int(input("Введите число: "))

if val < 0:

raise MyException("Число меньше нуля: " + str(val))

print(val + 10)

except MyException as e:

print(e)

Недостатки обработки исключений в Python

Базовые проблемы питона перекочевали в обработчик исключений, динамичность, множественное наследование, большой расход ресурсов. Также стоит отметить, что try except python в одну строку написать практически невозможно, без потери функциональности. В целом любая проблема решаема, главное — продумывать, как и когда использовать исключение.

Заключение

Не существует программиста, который способен писать код сразу, идеально, без малейших дефектов и уязвимостей. Python часто называют языком для новичков, но это не значит, что язык сделает все сам или додумает то, что не прописано. Исключения помогают избежать определённые ситуаций, не всех, но многих. Стоит помнить, что никакая дополнительная функция ошибок python не учит не совершать их вновь.

Следующие исключения являются исключениями, которые обычно возникают во время исполнения программы.

Содержание:

  • Исключение StopIteration
  • Исключение StopAsyncIteration
  • Исключение ArithmeticError
  • Исключение AssertionError
  • Исключение AttributeError
  • Исключение BufferError
  • Исключение EOFError
  • Исключение ImportError
    • Исключение ModuleNotFoundError
  • Исключение LookupError
    • Исключение IndexError
    • Исключение KeyError
  • Исключение MemoryError
  • Исключение NameError
    • Исключение UnboundLocalError
  • Исключение OSError
  • Исключение ReferenceError
  • Исключение RuntimeError
    • Исключение NotImplementedError
    • Исключение RecursionError
  • Исключение SyntaxError
    • Исключение IndentationError
    • Исключение TabError
  • Исключение SystemError
  • Исключение TypeError
  • Исключение ValueError
  • Исключение UnicodeError
  • Исключение EnvironmentError
  • Исключение IOError
  • Исключение WindowsError

StopIteration:

Исключение StopIteration вызывается встроенной функцией next() и методом итератора __next__(), чтобы сигнализировать, что итератор больше не производит никаких элементов.

Объект исключения имеет единственный атрибут value, который задается в качестве аргумента при создании исключения и по умолчанию равен None.

Когда функция генератора или сопрограммы возвращается, создается новый экземпляр StopIteration, и значение, возвращаемое функцией, используется в качестве параметра value для конструктора исключения.

Если код генератора прямо или косвенно поднимает StopIteration, он преобразуется в RuntimeError, сохраняя StopIteration как причину нового исключения.

StopAsyncIteration:

Исключение StopAsyncIteration вызывается методом __next__() объекта асинхронного итератора, чтобы остановить итерацию.

ArithmeticError:

AssertionError:

Исключение AssertionError вызывается когда оператор assert терпит неудачу.

AttributeError:

Исключение AttributeError вызывается при сбое ссылки на атрибут или присвоения. Если объект не поддерживает ссылки на атрибуты или назначения атрибутов вообще, вызывается TypeError.

BufferError:

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

EOFError:

Исключение EOFError вызывается когда функция input() попадает в состояние конца файла без чтения каких-либо данных. Когда методы io.IOBase.read() and io.IOBase.readline() возвращают пустую строку при попадании в EOF.

ImportError:

Исключение ImportError вызывается когда оператор import имеет проблемы при попытке загрузить модуль. Также ImportError поднимается, когда “из списка» в конструкция from ... import имеет имя, которое не может быть найдено.

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

  • ModuleNotFoundError:

    Исключение ModuleNotFoundError подкласс ImportError, который вызывается оператором import, когда модуль не может быть найден. Он также вызывается, когда в sys.modules имеет значение None.

LookupError:

Исключение LookupError — базовый класс для исключений, возникающих при недопустимости ключа или индекса, используемого в сопоставлении или последовательности: IndexError, KeyError. Исключение LookupError может быть вызван непосредственно codecs.lookup().

  • IndexError:

    Исключение IndexError вызывается когда индекс последовательности находится вне диапазона. Индексы среза усекаются без каких либо предупреждений, чтобы попасть в допустимый диапазон. Если индекс не является целым числом, поднимается исключение TypeError.

  • KeyError:

    Исключение KeyError вызывается когда ключ сопоставления словаря не найден в наборе существующих ключей.

MemoryError:

Исключение MemoryError вызывается, когда операции не хватает памяти, но ситуация все еще может быть спасена путем удаления некоторых объектов. Значение представляет собой строку, указывающую какой внутренней операции не хватило памяти. Обратите внимание, что из-за базовой архитектуры управления памятью интерпретатор не всегда может полностью восстановиться в этой ситуации. Тем не менее, возникает исключение, чтобы можно было напечатать трассировку стека.

NameError:

Исключение NameError вызывается, когда локальное или глобальное имя не найдено. Значение — это сообщение об ошибке, содержащее имя, которое не удалось найти.

  • UnboundLocalError:

    Исключение UnboundLocalError вызывается, когда ссылка сделана на локальную переменную в функции или методе, но никакое значение не было привязано к этой переменной. Это подкласс NameError.

OSError:

ReferenceError:

Исключение ReferenceError вызывается, когда слабый эталонный прокси-сервер, созданный функцией weakref.proxy() используется для доступа к атрибуту референта после сбора его мусора.

RuntimeError:

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

  • NotImplementedError:

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

    Заметки:

    1. Его не следует использовать для указания того, что оператор или метод вообще не предполагается поддерживать — в этом случае либо оставьте оператор/метод неопределенным, либо, установите его в None.
    2. NotImplementedError и NotImplemented не являются взаимозаменяемыми, даже если они имеют схожие имена и цели. Смотрите подробности NotImplemented о том, когда его использовать.
  • RecursionError:

    Исключение RecursionError получено из RuntimeError. Исключение RecursionError вызывается, когда интерпретатор обнаруживает, что максимальная глубина рекурсии sys.getrecursionlimit() превышена.

SyntaxError:

Исключение SyntaxError вызывается, когда синтаксический анализатор обнаруживает синтаксическую ошибку. Ошибка данного типа может произойти в инструкции import, при вызове встроенной функции exec() или eval(), или при чтении первоначального сценария или стандартный ввода, также в интерактивном режиме.

Экземпляры этого класса имеют атрибуты filename, lineno, offset и text для облегчения доступа к информации. Функция str() экземпляра исключения возвращает только сообщение.

  • IndentationError:

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

  • TabError:

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

SystemError:

Исключение SystemError вызывается, когда интерпретатор обнаруживает внутреннюю ошибку, но ситуация не выглядит настолько серьезной, чтобы заставить его отказаться от всякой надежды. Ассоциированное значение — это строка, указывающая, что пошло не так (в терминах низкого уровня).

TypeError:

Исключение TypeError вызывается, когда операция или функция применяется к объекту неподходящего типа. Связанное значение представляет собой строку, содержащую сведения о несоответствии типов.

Исключение TypeError может быть вызвано пользовательским кодом, чтобы указать, что попытка выполнения операции над объектом не поддерживается и не должна поддерживаться. Если объект предназначен для поддержки данной операции, но еще не предоставил реализацию, то вызывайте исключение NotImplementedError.

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

ValueError:

Исключение ValueError вызывается, когда операция или функция получает аргумент, который имеет правильный тип, но недопустимое значение, и ситуация не описывается более точным исключением, таким как IndexError.

UnicodeError:

EnvironmentError:

Доступно только в Windows.

IOError:

Доступно только в Windows.

WindowsError:

Доступно только в Windows.

I’m receiving an unhandled exception while debugging, and the program stops executing. The debugger doesn’t show me the line so I don’t know what to fix.

An unhandled exception of type ‘System.AggregateException‘ occurred in mscorlib.dll

Additional information: A Task’s exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.

Cannot obtain value of local or argument ‘<this>‘ as it is not available at this instruction pointer, possibly because it has been optimized away. System.Threading.Tasks.TaskExceptionHolder

How can I troubleshoot this problem?

I also found this question which is pretty similar.

CarenRose's user avatar

CarenRose

1,2661 gold badge12 silver badges23 bronze badges

asked Jun 20, 2012 at 14:45

Oleg Vazhnev's user avatar

Oleg VazhnevOleg Vazhnev

23.1k54 gold badges170 silver badges303 bronze badges

1

As the message says, you have a task which threw an unhandled exception.

Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.


(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the «Enable Just My Code» option.

T.Todua's user avatar

T.Todua

52.5k19 gold badges233 silver badges236 bronze badges

answered Jun 20, 2012 at 14:46

SLaks's user avatar

6

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

answered Jun 20, 2012 at 14:50

Darren's user avatar

DarrenDarren

68.6k24 gold badges136 silver badges144 bronze badges

2

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

answered Apr 21, 2015 at 12:23

helios456's user avatar

helios456helios456

1,62416 silver badges24 bronze badges

In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.

answered Jul 17, 2017 at 15:24

Nono's user avatar

NonoNono

1881 silver badge7 bronze badges

  • Remove From My Forums
  • Question

  • I am getting this error repeatedly on SQL Server 2008 on Windows machine when i run a simple query which involves close to ~ 10 million records.
    select sum(a.test) from (select COUNT(*) as test from xf.dbo.sec_mthprc s1 group by gvkey, datadate) a

    Technical Data:
       Sql Server 2008 : 2009-07-29 03:13:16.280 Server       Microsoft SQL Server 2008 (SP1) — 10.0.2531.0 (X64)
                                 Mar 29 2009 10:11:52
                                 Copyright (c) 1988-2008 Microsoft Corporation
                                 Developer Edition (64-bit) on Windows NT 6.0 <X64> (Build 6001: Service Pack 1)
       Microsoft Windows 2008 Standard Edition x64 with 16 GB RAM and 2 quad-core processors

Answers

  • Hi Pranav

    This is Mark Han, Microsoft Support SQL Engineer. I’m glad to assist you with the problem

    According to your description, I understand that when you running the command, the error(«Exception of type ‘System.OutOfMemoryException’ was thrown) will appear.

    in order to resolve the issue, I would like to explain the following
    1please veirfy that the tool you use to run the query is not 32-bit. if the tool is 32-bit, this kind of behavior is expected. Therefore, to resolve the issue, we need to use 64-bit Tool to run the sql command

    2 regarding to the error message, we could know the computer does not have sufficient memory to complete the requested operation. So let’s set the max memory for the sql server so that the sql won’t take as much momery as it can; and memory might be enough for the OS to complete the operation.

    3 to further diagnose the problem, we also need to check the memory status of the sql and the situation of the performance of the OS when the issue happens. So please help to post the following information
    a) can we always reproduce the issue?
    b) run dbcc memorystatus while the issue happens
    c) check the sql error log to see if there are some memory error logged

    if you have any questions on the above, please let me know. Thanks.

    Regards
    Mark Han

    • Marked as answer by

      Tuesday, August 11, 2009 4:46 AM

  • Hi Janathan

    Thank you for the update.

    since only 32-bit SQL Server Management Studio is available, we need to run the query by SQLCMD. The syntax as follows
    c:> sqlcmd -S»SQLInstanceName» -d»DbName» -i»InputFile.sql» -o»OutputFile»

    Also, we could run the 32-bit SQL Server Management Studio on a 32-bit OS and use the SSMS to connect to the 64-bit instance remotely.

    Besides, about more information, there is an article to share with you:http://support.microsoft.com/?id=906892

    if you have any questions on the above, please let me know.

    Regards
    Mark Han

    • Marked as answer by
      Mark Han [MSFT]
      Tuesday, August 11, 2009 4:46 AM

  • Could you check in your Task Manager the utilization of RAM. See whether your RAM is utilised upto 100%. Also, please mention the capacity of your server in terms of processor and RAM.

    If you have higher RAM — like about 4GB+ and its not being utilised maximum, then I would suggest you to check the 3G switch of your system.


    Microsoft Techie

    3GB doesn’t apply to 64 bit Servers which have a 8TB of user VAS exceeding the physical limits of RAM available in a single server currently.

    Hello Mate,

    As this SQL server is 64 bit, you need to make sure that you have min and Max server memory set. Because on 64 bit SQL server can take as much memory as it wants to take. So it is pretty much required to bound it to some limit.

    Can you please send the dbcc memorystatus output of the time when you are running the querry and the execution plan with statistics profile.

    Kind regards,
    Harsh Chawla


    Harsh Chawla

    One of the key things pointed out above is you need to set max server memory on the server.  This is a recommended best practice for all SQL Servers, but it is imperative for 64 bit environments which as I point out above have 8TB of VAS which makes over commitment of memory easy.  With 16GB if RAM I’d start somewhere around 12GB for SQL as a max if this is a dedicated SQL Server that is not running any other applications.  Then monitor the MemoryAvailable MBytes counter and increase the max server memory up from 12GB slowly making sure that the Available MBytes stays in the 100-150MB range at all times.  In addition to having max server memory set, you also will want to enable the Lock Pages in Memory right in the local security policy for the SQL Service Account.

    http://support.microsoft.com/kb/918483


    Jonathan Kehayias
    http://sqlblog.com/blogs/jonathan_kehayias/
    http://www.twitter.com/SQLSarg
    http://www.sqlclr.net/
    Please click the Mark as Answer button if a post solves your problem!

    • Marked as answer by
      Jonathan KehayiasMVP
      Monday, August 24, 2009 3:15 PM

Hi, I have a problem with booting my 3DS, I hope somebody can fix this problem.
I have a Old 3DS (EUR) with Luma3DS v10.0.1 (now I can’t know the SysNAND version, sorry). The console using Boot9Strap.

About the origin of the error, I don’t know very much what could have happened, I only know that after playing a little bit of a game, the next day the error started to occurred the error.

So, every time I power on the console, I get this on the screen:

An exception ocurred

Processor: ARM11 (core 1)
Exception type: undefined instruction
Current process: pm (0000000000000000)

Attach a picture with more info (sorry for low light level):

An exception occurred screen

More interesting info:

Luma3DS configuration/options:
Screen brightness: 4(X)
Splash: Off(X)
Splash duration: 1(X)
PIN lock: Off(X)

Enable loading external FIRMs and modules: ( )
Enable game patching: ( )
Show NAND or user string in System Settings: (X)
Show GBA boot screen in patched AGB_FIRM: ( )
Set developer UNITINFO: ( )
Disable Arm11 exception handlers: ( )

Dump file:
crash_dump_file.zip

I try with other ways but nothing :(

By beforehand, thanks.

Понравилась статья? Поделить с друзьями:
  • Ошибка an exception has occurred что делать
  • Ошибка an error occurred while writing
  • Ошибка an error occurred while starting roblox details httpsendrequest
  • Ошибка an error occurred while sending the request
  • Ошибка access violation at address 00408e8f in module