Types of Exception in Python

An exception is an unwanted event or abnormal condition that occurs when the program encounters an error (something in the program goes wrong) during the execution of a program. It is usually an object in Python that represents an error.

In general, errors that occur at runtime are called exceptions. In Python, there are two common types of exception errors that are as:

  • System-defined exceptions (Built-in exceptions)
  • User-defined exceptions (Custom exceptions)

System-defined Exceptions


System-defined exceptions are predefined types of exceptions that are already defined by the Python system. These exceptions are also called built-in-exceptions that are available in Python standard library collection to deal with common errors that may occur during the execution of program code.

Python provides a number of built-in exceptions to represent and handle various types of errors. With the help of built-in exception handlers, we can write robust and error-resistant code in the program. The built-in exception handler handles the exception in Python through the mechanism known as “try-except” block.

When an exception occurs in the try block, the appropriate exception handler code specified in the “except” block is executed, and displayed an error message that includes the name of the exception and details about the cause of the error. We have only to take the correct action to handle it.

Types of Standard Built-in Exception in Python


Python has a rich hierarchy of exception classes that designate to handle various types of exception errors. An Exception class is the base or parent class of all the built-in exception classes.

All the built-in exceptions are derived from this class and can handle all types of exception in Python. Some commonly used built-in exceptions in Python are as follows:

  • SyntaxError
  • IndentationError
  • NameError
  • TypeError
  • ValueError
  • ZeroDivisionError
  • FileNotFoundError
  • IndexError
  • KeyError
  • AttributeError
  • IOError
  • ImportError
  • ArithmeticError
  • OverflowError
  • MemoryError
  • KeyboardInterrupt
  • SystemExit
  • RuntimeError and many more.

Let’s understand each built-in exception in brief with the help of examples.

1. SyntaxError

This exception is raised when the interpreter finds a syntax error while executing the program code. The syntax errors generally occur in the program when we violate any grammatical rules of the programming language.


These errors are the most common types of errors and are much easier to correct than other errors since they usually generate a helpful error message that gives an idea about what is wrong in the program. Let’s understand it with some examples.

Example 1:

print "Scientech Easy"
Output:
      SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

The above code produces a syntax error because the print function does not have parenthesis for its parameters. The correct code is as:

print("Scientech Easy") # Output: Scientech Easy

Example 2:

x = int(input("Enter your first number ")
y = int(input("Enter your second number "))

In the above code, a syntax error occurred in the first line because the number of opening parenthesis must be matched with closing parenthesis. The correct code is as:

x = int(input("Enter your first number "))
y = int(input("Enter your second number "))

2. IndentationError

This exception is raised when indentation (such as inconsistent use of tabs and spaces) is not specified properly. When we write a program, Python uses indentation to nest blocks. Each line in a block must have the same indentation level. If this rule is broken, an IndentationError occurs. Look at the example below.


Example 3:

# This code intentionally causes an IndentationError
def func():
print("This function has incorrect indentation.")
    print("This line should be properly indented.")

# Calling the function to trigger the error
func()
Output:
       IndentationError: expected an indented block after function definition on line 2

In this example, the func() is defined with inconsistent indentation. The print() statement inside the function lacks proper indentation, causing an IndentationError. Python relies on indentation to define blocks of code, and any deviation from the expected indentation level may result in this error.

3. NameError

This type of exception occurs when an identifier or variable is not found in the local or global namespace. In other words, if non-existent identifier used, NameError exception occurs. Look at the example below on it.

Example 4:

# This code intentionally causes a NameError
def func():
    variable = 10
    print("The value of the variable is:", varible)

# Calling the function.
func()
Output:
       NameError: name 'varible' is not defined. Did you mean: 'variable'?

In this example, within the func(), there’s a typing mistake in the variable name used within the print() statement. The variable varible is misspelled; it should be variable. This mistake causes a NameError because Python cannot find a variable named varible.

4. TypeError

This type of exception occurs when invalid data type is supplied to an operation or function. It can be caused due to several possible reasons. They are:

  • Attempting to access elements within a string, list, or tuple using something other than an integer. For example, if we try to access elements of a list or characters of a string using a non-integer value (like a string, float, or any non-numeric value) as an index, Python raises an error, specifically a TypeError.
  • When we pass the wrong number of arguments to a function or method.
  • Mismatch between elements in a format string and element passed for conversion.

Example 5:

def div(a, b):
    result = a / b  # Attempting to divide two values
    return result

# Calling the function with incompatible types.
result = div("10", 2)  # Dividing a string by an integer
print("Result:", result)
Output:
       TypeError: unsupported operand type(s) for /: 'str' and 'int'

In this example, the div() function attempts to perform division on the arguments a and b. However, the first argument passed to the function is a string “10”, and the second argument is an integer 2. Attempting to divide a string by an integer results in a TypeError in Python because string division with an integer is not supported.

5. ValueError

The ValueError exception occurs when a built-in operation or function expects an argument of correct data type but receives an inappropriate or invalid value for that operation. Look at the example below:

Example 6:

def calculate_square_root(number):
    if number < 0:
        raise ValueError("ValueError: Cannot calculate square root of a negative number")
    else:
        return number ** 0.5

# Calling the function with an inappropriate value to trigger the error.
try:
    result = calculate_square_root(-9)  # Attempting to calculate square root of a negative number
    print("Square root:", result)
except ValueError as e:
    print(e)  # Displaying the error message
Output:
       ValueError: Cannot calculate square root of a negative number

In this code, the calculate_square_root() function calculates the square root of a number. However, if the argument passed to the function is a negative number, it raises a ValueError with a custom error message indicating that the square root cannot be calculated for negative numbers. The try-except block handles the ValueError exception raised within the function and displays the error message accordingly.

6. ZeroDivisionError

This type of exception occurs in a program when we attempt to divide a number by zero. Here’s an example code that raises a ZeroDivisionError:

Example 7:

def divide_numbers(a, b):
    result = a / b 
    return result

# Calling the function with a divisor of zero to trigger the error.
result = divide_numbers(8, 0)  # Attempting to divide by zero
print("Result:", result)  # This line will not execute due to the unhandled ZeroDivisionError
Output:
       ZeroDivisionError: division by zero

7. FileNotFoundError

The FileNotFoundError exception occurs when we attempt to open or access a file that does not exist. The below is an example code that causes a FileNotFoundError.

Example 8:

try:
    with open('nonexistent_file.txt', 'r') as file:
        content = file.read()
    print("File content:", content)  # This line won't be reached if FileNotFoundError occurs
except FileNotFoundError as e:
    print("File not found. Error:", e)  # Displaying the error message
Output:
       File not found. Error: [Errno 2] No such file or directory: 'nonexistent_file.txt'

In this example, we have attempted to open a file named ‘nonexistent_file.txt’ in read mode using the open() function within a try-except block. However, if the file does not exist in the specified location, a FileNotFoundError is raised. The except block catches this exception and prints an error message indicating that the file was not found, displaying the specific error generated by the FileNotFoundError.

8. IndexError

The IndexError exception occurs when we try to access an element of a sequence (like a string, list or tuple) using an invalid index number. Here’s an example code that triggers an IndexError without handling the exception:

Example 9:

numbers = [1, 2, 3]
# Attempting to access an index that exceeds the list length
result = numbers[4]  # Accessing index 4 which is out of range
print("Result:", result)  # This line won't be reached due to the unhandled IndexError
Output:
       IndexError: list index out of range

In this code snippet, there’s a list numbers containing three elements. We have attempted to access an index (numbers[4]) that exceeds the length of the list. Since Python lists are zero-indexed (i.e., the indices start from 0), therefore, access index 4 in a list with only three elements produces an IndexError because that index is out of range.

9. KeyError

The KeyError exception occurs in a program when we try to access a dictionary key that does not exist. Look at the below example.

Example 10:

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Attempting to access a non-existent key in the dictionary
value = my_dict['d']  # Accessing key 'd' which does not exist
print("Value:", value)  # This line won't be reached due to the unhandled KeyError
Output:
       KeyError: 'd'

In this code, there’s a dictionary my_dict with keys ‘a’, ‘b’, and ‘c’. We have attempted to access a key ‘d’ that does not exist in the dictionary. Therefore, a KeyError is raised during the attempt to access the non-existent key.

10. AttributeError

The AttributeErrorexception occurs in the program when we attempt to access an attribute or method that does not exist. If an AttributeError indicates that an object has NoneType, meaning it is None. Look at the below example.

Example 11:

class Student:
    def __init__(self):
        self.name = "Deepak"
        self.rollno = 10

# Creating an object of class.
st = Student()
print(st.id)
Output:
       AttributeError: 'Student' object has no attribute 'id'

11. IOError

The IOError exception occurs in the program when there is an input/output error, such as failing to open a non-existing file with the open() method. Look at the below example code that triggers an IOError.

Example 12:

# Trying to open a non-existent file in read mode.
fileName = open('nonexistent_file.txt', 'r')
Output:
       FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'

In this example, we have tried to open a file named ‘nonexistent_file.txt’ in read mode (‘r’) using open() function. This function open files and returns a file object. However, if the file ‘nonexistent_file.txt’ does not exist in the specified location or directory, an FileNotFoundError will occur, indicating that the specified file could not be found.

In Python versions prior to 3.3, attempting to open a non-existent file using the open() function in read mode (‘r’) would raise an IOError instead of the more specific FileNotFoundError.

In more recent versions of Python (3.3 and later), when a file does not exist in the specified location, attempting to open it using the open() function raised FileNotFoundError exception. The ‘r’ mode in the above line indicates that the file should be opened in read-only mode.

12. ImportError

This type of exception occurs in the program when an import statement fails or cannot find the specified module. Here’s an example code that triggers an ImportError error:

Example 13:

try:
    import my_module  # Attempting to import a non-existent module
    print("Module imported successfully")  # This line won't be executed if ImportError occurs
except ImportError as e:
    print("ImportError occurred. Error:", e)  # This line won't be executed without handling
Output:
       ImportError occurred. Error: No module named 'my_module'

In this example code, we have a Python file named my_module.py that does not exist or cannot be imported. An attempting to import a module named my_module that does not exist or cannot be imported, will raise an ImportError exception.

User-defined Exception in Python


A user-defined exception in Python is an exception that the programmer or user creates to represent a specific error condition or exceptional situation in the program. This type of exception is also called a custom exception. However, Python offers various types of built-in exceptions to handle common errors.

Even though there may be situations in which we may need to define our own custom exceptions to handle the specific errors in the application program or to add more context to error handling.


Conclusion

In this tutorial, we have explained types of exception in Python with the help of various example programs. We hope that you will have understood the basic definition of each exception and practiced all programs. In the next, we will understand try-except block in Python.
Thanks for reading!!!

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.