Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Try Except
Next article icon

Python Built-in Exceptions

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.

We can catch exceptions using try and except blocks, allowing your program to continue running even if an error occurs. These built-in exceptions can be viewed using the local() built-in functions as follows :

>>> locals()['__builtins__']

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

Python Built-in Exceptions

Here’s a table listing all the major Python built-in exceptions along with a brief :

Exception NameDescription
BaseExceptionThe base class for all built-in exceptions.
ExceptionThe base class for all non-exit exceptions.
ArithmeticErrorBase class for all errors related to arithmetic operations.
ZeroDivisionErrorRaised when a division or modulo operation is performed with zero as the divisor.
OverflowErrorRaised when a numerical operation exceeds the maximum limit of a data type.
FloatingPointErrorRaised when a floating-point operation fails.
AssertionErrorRaised when an assert statement fails.
AttributeErrorRaised when an attribute reference or assignment fails.
IndexErrorRaised when a sequence subscript is out of range.
KeyErrorRaised when a dictionary key is not found.
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a local or global name is not found.
OSErrorRaised when a system-related operation (like file I/O) fails.
TypeErrorRaised when an operation or function is applied to an object of inappropriate type.
ValueErrorRaised when a function receives an argument of the right type but inappropriate value.
ImportErrorRaised when an import statement has issues.
ModuleNotFoundErrorRaised when a module cannot be found.
IOErrorRaised when an I/O operation (like reading or writing to a file) fails.
FileNotFoundErrorRaised when a file or directory is requested but cannot be found.
StopIterationRaised when the next() function is called and there are no more items in an iterator.
KeyboardInterruptRaised when the user presses Ctrl+C or interrupts the program’s execution.
SystemExitRaised when the sys.exit() function is called to exit the program.
NotImplementedErrorRaised when an abstract method that needs to be implemented is called.
RuntimeErrorRaised when a general error occurs in the program.
RecursionErrorRaised when the maximum recursion depth is exceeded.
SyntaxErrorRaised when there is an error in the syntax of the code.
IndentationErrorRaised when there is an indentation error in the code.
TabErrorRaised when the indentation consists of inconsistent use of tabs and spaces.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.

Let’s understand each exception in detail:

1. BaseException

The base class for all built-in exceptions. Example:

Python
try:     raise BaseException("This is a BaseException") except BaseException as e:     print(e) 

Output
This is a BaseException 

Explanation: This code manually raises a BaseException and catches it, printing the exception message.

2. Exception

The base class for all non-exit exceptions. Example:

Python
try:     raise Exception("This is a generic exception") except Exception as e:     print(e) 

Output
This is a generic exception 

Explanation: This raises a generic Exception and handles it, printing the message.

3. ArithmeticError

Base class for all errors related to arithmetic operations. Example:

Python
try:     raise ArithmeticError("Arithmetic error occurred") except ArithmeticError as e:     print(e) 

Output
Arithmetic error occurred 

Explanation: This raises an ArithmeticError and catches it, displaying the error message.

4. ZeroDivisionError

Raised when a division or modulo operation is performed with zero as the divisor. Example:

Python
try:     result = 10 / 0 except ZeroDivisionError as e:     print(e) 

Output
division by zero 

Explanation: This code attempts to divide by zero, causing a ZeroDivisionError.

5. OverflowError

Raised when a numerical operation exceeds the maximum limit of a data type. Example:

Python
import math  try:     result = math.exp(1000)  # Exponential function with a large argument except OverflowError as e:     print(e) 

Output
math range error 

Explanation: The exponential function with a large argument causes an OverflowError.

6. FloatingPointError

Raised when a floating-point operation fails. Example:

Python
import sys import math  sys.float_info.max = 1.79e+308  # Maximum float value  try:     math.sqrt(-1.0)  # This doesn't raise a FloatingPointError by default except FloatingPointError as e:     print(e) 

Explanation: Floating-point errors are rare in Python; this code demonstrates the typical use case.

7. AssertionError

Raised when an assert statement fails. Example:

Python
try:     assert 1 == 2, "Assertion failed" except AssertionError as e:     print(e) 

Output
Assertion failed 

Explanation: This code fails an assertion, raising an AssertionError.

8. AttributeError

Raised when an attribute reference or assignment fails. Example:

Python
class MyClass:     pass  obj = MyClass()  try:     obj.some_attribute except AttributeError as e:     print(e) 

Output
'MyClass' object has no attribute 'some_attribute' 

Explanation: This code tries to access a non-existent attribute, causing an AttributeError.

9. IndexError

Raised when a sequence subscript is out of range. Example:

Python
my_list = [1, 2, 3]  try:     element = my_list[5] except IndexError as e:     print(e) 

Output
list index out of range 

Explanation: This code tries to access an out-of-range index in a list, raising an IndexError.

10. KeyError

Raised when a dictionary key is not found. Example:

Python
d = {"key1": "value1"}  try:     val = d["key2"] except KeyError as e:     print(e) 

Output
'key2' 

Explanation: This code attempts to access a non-existent dictionary key, causing a KeyError.

11. MemoryError

Raised when an operation runs out of memory. Example:

Python
try:     li = [1] * (10**10) except MemoryError as e:     print(e) 

Explanation: This code tries to create a very large list, causing a MemoryError.

12. NameError

Raised when a local or global name is not found. Example:

Python
try:     print(var) except NameError as e:     print(e) 

Output
name 'var' is not defined 

Explanation: This code attempts to use an undefined variable, raising a NameError.

13. OSError

Raised when a system-related operation (like file I/O) fails. Example:

Python
try:     open("non_existent_file.txt") except OSError as e:     print(e) 

Output
[Errno 2] No such file or directory: 'non_existent_file.txt' 

Explanation: This code tries to open a non-existent file, causing an OSError.

14. TypeError

Raised when an operation or function is applied to an object of inappropriate type. Example:

Python
try:     result = '2' + 2 except TypeError as e:     print(e) 

Output
can only concatenate str (not "int") to str 

Explanation: This code tries to add a string and an integer, causing a TypeError.

15. ValueError

Raised when a function receives an argument of the right type but inappropriate value. Example:

Python
try:     res = int("abc") except ValueError as e:     print(e) 

Output
invalid literal for int() with base 10: 'abc' 

Explanation: This code tries to convert a non-numeric string to an integer, raising a ValueError.

16. ImportError

Raised when an import statement has issues. Example:

Python
try:     import mod except ImportError as e:     print(e) 

Output
No module named 'mod' 

Explanation: This code attempts to import a non-existent module, causing an ImportError.

17. ModuleNotFoundError

Raised when a module cannot be found. Example:

Python
try:     import module except ModuleNotFoundError as e:     print(e) 

Output
No module named 'module' 

Explanation: Similar to ImportError, this code tries to import a module that doesn’t exist.

18. IOError

Raised when an I/O operation (like reading or writing to a file) fails. Example:

Python
try:     open("non_existent_file.txt") except IOError as e:     print(e) 

Output
[Errno 2] No such file or directory: 'non_existent_file.txt' 

Explanation: This is another example of file-related errors, causing an IOError.

19. FileNotFoundError

Raised when a file or directory is requested but cannot be found. Example:

Python
try:     open("non_existent_file.txt") except FileNotFoundError as e:     print(e) 

Output
[Errno 2] No such file or directory: 'non_existent_file.txt' 

Explanation: This specifically catches the FileNotFoundError when trying to open a missing file.

20. StopIteration

Raised when the next() function is called and there are no more items in an iterator. Example:

Python
my_iter = iter([1, 2, 3])  try:     while True:         print(next(my_iter)) except StopIteration as e:     print("End of iterator") 

Output
1 2 3 End of iterator 

Explanation: This code iterates through a list and raises StopIteration when the list is exhausted.

21. KeyboardInterrupt

Raised when the user presses Ctrl+C or interrupts the program’s execution. Example:

Python
try:     while True:         pass except KeyboardInterrupt as e:     print("Program interrupted by user") 

Explanation: This code runs an infinite loop until the user interrupts it with Ctrl+C.

22. SystemExit

Raised when the sys.exit() function is called to exit the program. Example:

Python
import sys  try:     sys.exit() except SystemExit as e:     print("System exit called") 

Output
System exit called 

Explanation: This code calls sys.exit(), raising a SystemExit exception.

23. NotImplementedError

Raised when an abstract method that needs to be implemented is called. Example:

Python
class BaseClass:     def some_method(self):         raise NotImplementedError("This method should be overridden")  try:     obj = BaseClass()     obj.some_method() except NotImplementedError as e:     print(e) 

Output
This method should be overridden 

Explanation: This code demonstrates a base class method that should be overridden in subclasses, raising NotImplementedError if called.

24. RuntimeError

Raised when a general error occurs in the program. Example:

Python
try:     raise RuntimeError("A runtime error occurred") except RuntimeError as e:     print(e) 

Output
A runtime error occurred 

Explanation: This manually raises a RuntimeError and catches it.

25. RecursionError

Raised when the maximum recursion depth is exceeded. Example:

Python
try:     def recursive_function():         recursive_function()      recursive_function() except RecursionError as e:     print(e) 

Output
maximum recursion depth exceeded 

Explanation: This code defines a recursive function that calls itself indefinitely, causing a RecursionError.

26. SyntaxError

Raised when there is an error in the syntax of the code. Example:

Python
try:     eval('x === 2') except SyntaxError as e:     print(e) 

Output
invalid syntax (<string>, line 1) 

Explanation: This code uses eval() to evaluate an incorrect syntax, raising a SyntaxError.

27. IndentationError

Raised when there is an indentation error in the code. Example:

Python
try:     eval('def func():\n  print("Hello")\n print("World")') except IndentationError as e:     print(e) 

Explanation: This code uses eval() to evaluate code with incorrect indentation, causing an IndentationError.

28. TabError

Raised when the indentation consists of inconsistent use of tabs and spaces. Example:

Python
try:     eval('def func():\n\tprint("Hello")\n    print("World")') except TabError as e:     print(e) 

Explanation: This code uses eval() to evaluate code with mixed tabs and spaces, causing a TabError.

29. UnicodeError

Raised when a Unicode-related encoding or decoding error occurs. Example:

Python
try:     'æ'.encode('ascii') except UnicodeError as e:     print(e) 

Output
'ascii' codec can't encode character '\xe6' in position 0: ordinal not in range(128) 

Explanation: This code tries to encode a non-ASCII character using the ASCII codec, raising a UnicodeError.



Next Article
Python Try Except

A

Aditi Gupta
Improve
Article Tags :
  • Python
  • Python-exceptions
Practice Tags :
  • python

Similar Reads

  • __import__() function in Python
    __import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
    2 min read
  • Python Classes and Objects
    A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
    6 min read
  • Constructors in Python
    In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
    3 min read
  • Destructors in Python
    Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
    7 min read
  • Inheritance in Python
    Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
    7 min read
  • Encapsulation in Python
    In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
    6 min read
  • Polymorphism in Python
    Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
    7 min read
  • Class method vs Static method in Python
    In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
    5 min read
  • File Handling in Python
    File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
    7 min read
  • Reading and Writing to text files in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences