Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Base Classes
2.1.
BaseException
2.2.
Exception
2.3.
ArithmeticError
2.4.
BufferError
2.5.
LookupError
3.
Concrete Exceptions
3.1.
AssertionError
3.2.
AttributeError
3.3.
EOFError
3.4.
GeneratorExit
3.5.
ImportError
3.6.
IndexError
3.7.
KeyError
3.8.
KeyboardInterrupt
3.9.
MemoryError
3.10.
NameError
3.11.
NotImplementedError
3.12.
OSError([arg])
3.13.
OverflowError
3.14.
RecursionError
3.15.
RuntimeError
3.16.
StopIteration
3.17.
SyntaxError
3.18.
SystemError
3.19.
TypeError
3.20.
ValueError
3.21.
ZeroDivisionError
4.
FAQs
5.
Conclusion
Last Updated: Mar 27, 2024

Built-in Exception in Python

Author ANKIT KUMAR
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Even if any statement or expression is syntactically correct, it may produce an error when executed. Exceptions are errors that occur during execution. In Python, all the exception classes are derived from the BaseException class.

All other exceptions are derived from the BaseException. User-defined classes cannot be directly derived from this class; instead, we must use the Exception class to derive user-defined classes. The Exception class is also derived from the BaseException class.

In order to get the list of all the built-in exceptions in Python we can use the following code:

print(dir(locals()['__builtins__']))

This code displays a dictionary of built-in exceptions, functions, and attributes.

Also SEE, Floor Division in PythonFibonacci Series in Python

Base Classes

The following exception classes are used mostly as base classes for other exceptions.

BaseException

The BaseException is the base class for all built-in exceptions. All the exception classes are derived from this class. It is not directly inherited by user-defined classes. For user-defined classes, the Exception class is used. This class creates a string representation of the exception using str() using the arguments passed.

Exception

All user-defined classes are derived from this class. This is one of the most commonly used exception classes. It also serves as the base class for all built-in non-system-exiting exceptions.

ArithmeticError

The ArithmeticError exception class serves as a base class for those built-in exceptions that are raised due to various arithmetic errors like OverflowError, ZeroDivisionError, FloatingPointError.

Example of ArithmeticError Exception:

print(5/0)

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero

It can be seen that dividing five by zero results in ZeroDivisionError, which is a child of the ArithmeticError class.

BufferError

The BufferError exception is raised when buffer-related operations cannot be performed.

LookupError

This type of error is generally encountered while using maps. The LookupError raises two exceptions which are KeyError and IndexError. It serves as the base class for exceptions that result due to invalid keys or indexes used on a mapping or sequence.

Example:

CN_courses=["DSA", "Python", " Java", "Web Development"]

// it will throw IndexError (a child of LookUp Error)
print(CN_courses[5])

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(CN_courses[5])
IndexError: list index out of range

 

You can try it on online python compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Concrete Exceptions

The following are some of the commonly raised exceptions that programmers encounter often.

AssertionError

The AssertionError is raised when an assert statement is false.

Example:

# function to determine the length of the list given
# It also asserts if the length is zero or not 
# In case of an empty list it throw a AssertionError with the message provided.
def length(List):
    assert len(List)!=0, "No courses available!"
    return len(List)
    
CN_courses=[]
list_length= length(CN_courses)
print(list_length)

Output:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    list_length= length(CN_courses)
  File "main.py", line 5, in length
    assert len(List)!=0, "No courses available!"
AssertionError: No courses available!

AttributeError

The AttributeError is raised when an attribute reference or assignment fails.

Example:

# program to illustrate AttributeError
# Strings do not have append() attribute
str1="Coding"
str2="Ninjas"

# This results in AttributeError
str3= str1.append(str2)
print(str3)

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    str3= str1.append(str2)
AttributeError: 'str' object has no attribute 'append'

EOFError

The EOFError is raised when the input() function reaches an end-of-file condition (EOF) without reading any data.

Example:

# program to demonstrate EOFError

# Take first string as the input 
str1= input()

# Print the string
print(str1)

# before taking the second string as input 
# press ctrl+D to interrupt the program and quit the process
# this will raise an EOFError as the second input was not taken
str2= input()
print(str2)

Output:

Coding
Coding
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    str2= input()
EOFError

GeneratorExit

The GeneratorExit is not considered to be an error directly. It inherits from the BaseException class rather than the Exception class. This exception is raised when a generator or a coroutine is closed.

ImportError

As the name says, this exception is raised when the program is unable to load the module which the user imports. In most cases either the module is not present at all or the name specified is wrong.

Example:

import CodingNinjas

Output: 

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import CodingNinjas
ModuleNotFoundError: No module named 'CodingNinjas'

The ModuleNotFoundError is a subclass of ImportError.

IndexError

This type of error is mostly raised when we try to access an illegal index. By illegal index, we mean the index which is out of range of the array or list.

Example:

a=["Coding", "Ninjas"]

# prints Ninjas
#print(a[1])

#IndexError
print(a[4])

Output:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(a[4])
IndexError: list index out of range

KeyError

This error is raised in case a key is tried to be accessed in the mapping, which is not available.

Example:

batsman = { 'Virat':1, 'Dhawan':2, 'Rohit':3 }

# key Dhoni is not present, hence it will raise KeyError
print (batsman['Dhoni'])

Output: 

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print (batsman['Dhoni'])
KeyError: 'Dhoni'

KeyboardInterrupt

This exception inherits from the BaseException so that it is not caught by the code that catches Exception. This exception generally arises when the user hits the interrupt key (normally Control-C or Delete).

Example:

#instead of providing any input press ctrl+c 
inp= input()
print(inp)

Output:

^CTraceback (most recent call last):
  File "main.py", line 1, in <module>
    inp= input()
KeyboardInterrupt

MemoryError

This exception is raised when the program runs out of memory.

Example:

my_list=[]
num= 99999999999
for i in range(num):
    my_list.append(i)
print(my_list)

Output: 

MemoryError

NameError

The NameError exception is raised when a local or global name is not found—for example, an unqualified variable name.

Example:

first="Coding"
second= "Ninjas"

# prints Coding
print(first)

# prints Ninjas
print(second)

# it will raise NameError before third is not defined
print(third)

Output: 

Coding
Ninjas
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(third)
NameError: name 'third' is not defined

NotImplementedError

The NotImplementedError occurs in Python when an abstract method lacks the required derived class to override this method, resulting in this exception.

OSError([arg])

This type of exception is raised in case of I/O failures like file not found or in case of system-related errors.

OverflowError

When the result of an arithmetic operation is out of range, the OverflowError is raised. Integers throw MemoryError rather than OverflowError. OverflowError is occasionally thrown for integers that are outside of a specified range. Floating-point values do not throw OverflowError.

Example:

import math

# results in Overflow
x= math.exp(1000)
print(x)

Output: 

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    x= math.exp(1000)
OverflowError: math range error

RecursionError

This error is generated when there is infinite recursion. When there is no terminating condition in the recursive function after some time, maximum recursion depth is exceeded, and an exception is raised.

Example:

# recursive function without terminating condition
def recur():
    print("Infinite recursion")
    recur()
# calling recur()
recur()

Output: 

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    recur()
  File "main.py", line 4, in recur
    recur()
  File "main.py", line 4, in recur
    recur()
  File "main.py", line 4, in recur
    recur()
  [Previous line repeated 992 more times]
  File "main.py", line 3, in recur
    print("Infinite recursion")
RecursionError: maximum recursion depth exceeded while calling a Python object.

RuntimeError

A program that has a runtime error has passed the interpreter's syntax checks and begun to execute. However, an error occurred during the execution of one of the program's statements, causing the interpreter to stop executing the program and display an error message. Runtime errors are also known as exceptions because they typically indicate that something unusual has occurred.

StopIteration

The StopIteration error is raised by the built-in function __next__() method. This exception is reached when the iterator tries to access an element that is not available. In such a case, the __next__() method tries to access a value, but no value is available.

Example:

arr = ["Coding", "Ninjas", "Blogs"]
itr=iter(arr)

print (itr)
print (itr.__next__())
print (itr.__next__())
print (itr.__next__())
print (itr.__next__())

Output: 

<list_iterator object at 0x7f36e84dd5e0>
Coding
Ninjas
Blogs
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print (itr.__next__())
StopIteration

SyntaxError

The SyntaxError is raised when the parser encounters a syntax error.

Example:

name="Coding Ninjas"

# we dont provide : after the if statement
# this will raise a SyntaxError
if name=="Coding Ninjas"
    print("Correct!")
else:
    print("Incorrect!")

Output:

File "main.py", line 5
    if name=="Coding Ninjas"
                           ^
SyntaxError: invalid syntax

SystemError

This error is raised when the interpreter detects an internal error. The user may not be responsible for this error.

TypeError

When an operation or function is applied to an object of the wrong type, a TypeError is thrown. This exception throws a string containing information about the type mismatch.

Example:

name="Coding Ninjas"
arr=[]

# concatenating string with list
# This will raise TypeError
temp=name+arr
print(temp)

Output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    temp=name+arr
TypeError: can only concatenate str (not "list") to str

ValueError

The ValueError is raised when an invalid value is provided to a particular data type.

Example:

name="Coding Ninjas"

# converting string to int will raise ValueError
print(int(name))

Output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(int(name))
ValueError: invalid literal for int() with base 10: 'Coding Ninjas'

ZeroDivisionError

This error is generated when a division operation is performed such that the denominator is zero.

Example:

print(5/0)

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero

Also see,  Convert String to List Python

FAQs

1.What are exceptions?

Exceptions are errors that occur during execution. In Python, all the exception classes are derived from the BaseException class.

2. What is the difference between BaseException and Exception class in Python?

BaseException class is not directly inherited by user-defined classes, whereas user-defined classes are derived from the Exception class.

3. Name a few errors that can raise ArithmeticError exceptions.

ArithmeticError exceptions are raised by arithmetic errors like OverflowError, ZeroDivisionError, FloatingPointError.

4. Name some commonly encountered errors.

Some commonly encountered errors are SyntaxError, TypeError, IndexError, ZeroDivisionError, KeyError and ImportError.

Conclusion

In this article, we have extensively discussed built-in exceptions in Python, along with a code demonstration of various exceptions.

  • Exceptions are errors that occur during execution. In Python, all the exception classes are derived from the BaseException class.
  • Some commonly encountered errors are SyntaxError, TypeError, IndexError, ZeroDivisionError, KeyError and ImportError.
     

Recommended Readings:

We hope that this blog has helped you enhance your knowledge regarding built-in exceptions in Python and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
User-defined Exception in Python
Next article
Clean-up Action In Python
Live masterclass