Exceptions in Python

In this tutorial, we will be learning about Exceptions. So without further ado, let’s get started.

What is an Exception?

The very first question that pops up in our minds.

An Exception is an unexpected problem or issue that alters the normal flow of execution.

What is an Exception in Python?

Exception in Python is an event that occurs at runtime which disrupts the flow of execution of a program and terminates it abnormally if left unhandled.

Whenever an exception occurs, our program stops executing and returns an error traceback taking user to the error along with its details.

For Example, the exception ZeroDivisionError occurs when we divide a number by 0.

def division(a,b):

In output, we get an exception with traceback

Traceback (most recent call last):
  File "main.py", line 4, in <module>
  File "main.py", line 2, in division
ZeroDivisionError: division by zero

Types of exceptions

There are 2 types of exceptions in Python

  1. Built-in
  2. User-defined

Built-in exceptions

Following are some of the Built-in exceptions provided by Python.

AssertionErrorFailed assert statement
AttributeErrorFailed attribute reference or assignment
EOFErrorReached end-of-file (EOF) without reading any data from raw_input() or input() (Python 2.7 & Python 3.x respectively)
ImportErrorImport statement failed to load a module or it was not found
IndexErrorIndex is not within the range (Generally while traversing in lists)
KeyboardInterruptAn unexpected key press interruption occurred (like Ctrl-C)
MemoryErrorExecution ran out of memory
NameErrorLocal or global variable name not found
OverflowErrorArithmetic result is too large to represent
ReferenceErrorObject referred already removed by Garbage Collector
RuntimeErrorWhen no matching category found
SyntaxErrorSyntax error found while parsing the code
IndentationErrorUnexpected or incorrect indentation
TabErrorInconsistant use of spaces or tabs for indentation
TypeErrorOperation performed between incompatible types
TimeoutErrorProgram not executed within a timeframe
UnboundLocalErrorLocal variable referred but no value bounded to it
UnicodeErrorError in unicode related encoding or decoding
ValueErrorNot a TypeError but unexpected value provided
ZeroDivisionErrorNumber divided by zero

We handle the exceptions raised using try, except and finally statements.

For User-defined exceptions and Exception handling, visit Exception handling in Python.

Help us improve this content by editing this page on GitHub