Exceptions in Python

One of most important aspect of any programming language is – How it deals with Errors? Usually whenever some programmer writes a piece of code there exists some chances of code raising Errors while executing it. If your code have Errors in it, then chances are high that without fixing these you will not be able to completely make a program. Whenever I work on a project of developing some program using Python, I usually do testing as I write code. This helps to identify source of Error easily and fix it.

But how does Python shows these Errors to programmer, its done by raising Exceptions. Its same like when you order something online and totally different product come to your home then you raise a complaint to online retailer. Similiarly if Python Interpreter is expecting a Tab in code and you instead have coded a Space then Interpreter will say Ohhh!! That’s wrong.

Let’s deep dive into Python Exception Class to see what kind of Errors can Python raise?

Python Exception Class

Python have a built-in exception class which is a Base-Class for all other Exception Classes in Python. Moreover if your defining some error catching procedure for class which you have defined yourself in Code, then its always recommended to inherit from built-in Base Class Exception.
Exception Class can raise two types of Errors in Python

  • Syntax Errors – Raised when Python Interpreter sees that code is not properly formatted.
  • Logical Errors – These errors are raised on run-time, when Python Interpreter tries to compute something which is not supported by Python Language itself like Zero Division.

Concrete Exceptions in Python – Table

AssertionErrorRaised when assert statment fails
AttributeErrorRaised when an attribute reference or assignment fails
EOFErrorRaised when input() function hits an end of file condition without reading any data
GeneratorExitRaised when generator or coroutine is closed
ImportErrorRaised when Python Interpreter either fails to load a module or when specified function to be imported doesn’t exist inside module itself.
ModuleNotFoundErrorRaised when Python interpreter cannot locate a module
IndexErrorRaised when you try to access some index of a Python Sequence which doesn’t exist
KeyErrorWhen a key is not found inside Dictionary, this error is raised
KeyboardInterruptUsually raised when interrupt key(Control and C key or delete) is pressed
MemoryErrorWhen run-time operations doesn’t left with enough memory for their execution
NameErrorRaised when Python doesn’t find name of some identity(Set, list, Dictionary or something else)
NotImplementedErrorRaised when exception handling code is not defined for class defined by programmer. Usually used for while writing classes for real time testing
OSErrorRaised for System-related errors like when some file is not found by Python Interpreter
OverflowErrorRaised when result of some arithmetic operation cannot be represented
RecursionErrorRaised when Interpreter detects that maximum recursion depth has been reached
RuntimeErrorRaised when interpreter found some error which it cannot classify as some Error type
StopIterationRaised by built-in next() function when there are no further items being produced by the iterator
StopAsyncIterationMust be raised by __anext__() method of an asynchronous iterator object to stop the iteration
SyntaxErrorRaised when parser cannot figure out syntax of code
IndentationErrorRaised when Python code is not properly indented
TabErrorRaised when indentation of code does not have proper tabs/spaces
SystemErrorRaised when some internal error in Python Interpreter occurs
SystemExitRaised when Python Interpreter exits and return some status code
TypeErrorRaised when an operation or function is applied to an object of inappropriate type
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable
UnicodeErrorRaised when a Unicode-related encoding/decoding error occurs
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translating
ValueErrorRaised when an operation or function receives an argument that has the right type but an inappropriate value
ZeroDivisionErrorRaised when the second argument of a division or modulo operation is zero

Operating Systems Exceptions in Python – Table

BlockingIOErrorRaised when an operation would block on an object (e.g. socket) set for non-blocking operation
ChildProcessErrorRaised when an operation on a child process failed
ConnectionErrorConnection related errors
BrokenPipeErrorRaised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing
ConnectionAbortedErrorRaised when a connection attempt is aborted by the peer
ConnectionRefusedErrorRaised when a connection attempt is refused by peer
ConnectionResetErrorRaised when a connection is reset by the peer
FileExistsErrorRaised when trying to create a file or directory which already exists
FileNotFoundErrorRaised when a file/directory is requested but doesn’t exist
InterruptedErrorRaised when a system call is interrupted by an incoming signal
IsADirectoryErrorRaised when a file operation is requested on a directory
NotADirectoryErrorRaised when a directory operation is requested on something which is not a directory
PermissionErrorRaised when trying to run an operation without the adequate access rights 
ProcessLookupErrorRaised when a given process doesn’t exist
TimeoutErrorRaised when a system function timed out at system level

Warning Exceptions in Python – Table

DeprecationWarningBase class for warnings about deprecated features when those warnings are intended for other Python developers
PendingDeprecationWarningBase class for warnings about features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment
SyntaxWarningBase class for warnings about dubious syntax
RuntimeWarningBase class for warnings about dubious runtime behavior
FutureWarningBase class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python
ImportWarningBase class for warnings about probable mistakes in module imports
UnicodeWarningBase class for warnings related to Unicode
BytesWarningBase class for warnings related to bytes and bytearray
ResourceWarningBase class for warnings related to resource usage

Exception Class Hierarchy in Python

 +-- 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

Final Thoughts

Well as of now, if you have gone through whole of article you may have become familiar with different types of Exception Errors in Python. But as a programmer the biggest challenge is to find ways to solve these Errors because for most of these errors, names itself speak its meaning like TypeError related to something with different types. (Quite Simple)

How to solve Exception Errors in Python? If in case your total beginner then it would be really difficult to solve these errors by self, so I would recommend using Google and StackOverFlow for finding out solutions for these errors. Also as you get to solve more and more of these errors, your skill of pinning down to source of Error and then knocking it out of code will improve.

That’s my personal experience, I still remember writing my first piece of Python Code and when running it seeing Syntax error 😰😥it almost took me an hour to find why error is coming up and then only I got a way to get rid of this Syntax error.

The more you write code, the better you become.
Happy Coding 🥳

Leave a Comment