Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Explain different type of error in python

SyntaxError

IndentationError

NameError

TypeError

ValueError

ZeroDivisionError

IndexError

KeyError

FileNotFoundError

AttributeError

PermissionError

FileExistsError

OSError

EOFError

ArithmeticError

FloatingPointError

ImportError

ModuleNotFoundError

MemoryError

RecursionError

GeneratorExit

SystemExit

KeyboardInterrupt

StopIteration

Exception handling in Python is essential for gracefully dealing with errors and exceptions that can occur during program execution. Here are 30 different types of exceptions in Python, along with examples of how to handle them:

SyntaxError:

Explanation: Raised when there's a syntax error in the code.

Example:

def my_function()
    pass  # Missing colon, raises SyntaxError
Enter fullscreen mode Exit fullscreen mode

IndentationError:

Explanation: Occurs when there's an indentation-related error.

Example:

if True:
print("Indented incorrectly")  # Raises IndentationError
Enter fullscreen mode Exit fullscreen mode

NameError:

Explanation: Raised when a variable or name is not found in the current scope.

Example:

print(undefined_variable)  # Raises NameError
Enter fullscreen mode Exit fullscreen mode

TypeError:

Explanation: Occurs when an operation is performed on an inappropriate data type.

Example:

result = "5" + 5  # Raises TypeError
Enter fullscreen mode Exit fullscreen mode

ValueError:

Explanation: Raised when a built-in operation or function receives an argument of the correct type but with an inappropriate value.

Example:

num = int("abc")  # Raises ValueError
Enter fullscreen mode Exit fullscreen mode

ZeroDivisionError:

Explanation: Occurs when attempting to divide by zero.

Example:

result = 1 / 0  # Raises ZeroDivisionError
Enter fullscreen mode Exit fullscreen mode

IndexError:

Explanation: Raised when trying to access an element of a list or sequence using an index that is out of bounds.

Example:


my_list = [1, 2, 3]
element = my_list[5]  # Raises IndexError
Enter fullscreen mode Exit fullscreen mode

KeyError:

Explanation: Occurs when trying to access a dictionary key that does not exist.

Example:

my_dict = {"key1": "value1"}
value = my_dict["key2"]  # Raises KeyError
Enter fullscreen mode Exit fullscreen mode

FileNotFoundError:

Explanation: Raised when trying to open a file that does not exist.

Example:

with open("nonexistent.txt", "r") as file:
    content = file.read()  # Raises FileNotFoundError
Enter fullscreen mode Exit fullscreen mode

AttributeError:

Explanation: Occurs when trying to access an attribute or method that does not exist on an object.

Example:

class MyClass:
    def __init__(self):
        self.value = 42

obj = MyClass()
result = obj.nonexistent_method()  # Raises AttributeError
Enter fullscreen mode Exit fullscreen mode

PermissionError:

Explanation: Raised when an operation that requires special permissions is denied.

Example:

with open("/root/sensitive.txt", "w") as file:
    file.write("This requires special permissions")  # Raises PermissionError
Enter fullscreen mode Exit fullscreen mode

FileExistsError:

Explanation: Occurs when trying to create a f*ile or directory that already exists*.

Example:

import os

os.mkdir("my_directory")
os.mkdir("my_directory")  # Raises FileExistsError
Enter fullscreen mode Exit fullscreen mode

OSError:

Explanation: A general exception for I/O-related errors.

Example:

try:
    file = open("/root/sensitive.txt", "r")
except OSError as e:
    print(f"OSError: {e}")
Enter fullscreen mode Exit fullscreen mode

EOFError:

Explanation: Raised when there is no input to read from a file or the user cancels the input operation.

Example:

try:
    user_input = input("Enter something: ")
    print(f"You entered: {user_input}")
except EOFError:
    print("No input provided")
Enter fullscreen mode Exit fullscreen mode

ArithmeticError:

Explanation: A base class for arithmetic errors.

Example:

try:
    result = 1 / 0  # Raises ZeroDivisionError (subclass of ArithmeticError)
except ArithmeticError as e:
    print(f"ArithmeticError: {e}")
Enter fullscreen mode Exit fullscreen mode

FloatingPointError:

Explanation: Raised when a floating-point operation fails.

Example:

try:
    result = 1.0 / 0.0  # Raises FloatingPointError
except FloatingPointError as e:
    print(f"FloatingPointError: {e}")
Enter fullscreen mode Exit fullscreen mode

ImportError:

Explanation: Occurs when an imported module is not found.

Example:

try:
    import non_existent_module  # Raises ImportError
except ImportError as e:
    print(f"ImportError: {e}")
Enter fullscreen mode Exit fullscreen mode

ModuleNotFoundError:

Explanation: Raised when an imported module is not found (Python 3.6+).

Example:

try:
    import non_existent_module  # Raises ModuleNotFoundError
except ModuleNotFoundError as e:
    print(f"ModuleNotFoundError: {e}")
Enter fullscreen mode Exit fullscreen mode

MemoryError:

Explanation: Occurs when there's not enough memory available.

Example:

try:
    big_list = [0] * 1000000000  # Raises MemoryError
except MemoryError as e:
    print(f"MemoryError: {e}")
Enter fullscreen mode Exit fullscreen mode

RecursionError:

Explanation: Raised when the maximum recursion depth is exceeded.

Example:

def recursive_function(n):
    return recursive_function(n - 1)  # Raises RecursionError when n is too large
Enter fullscreen mode Exit fullscreen mode

GeneratorExit:

Explanation: Raised when a generator's close() method is called.

Example:

def my_generator():
    try:
        yield 1
        yield 2
    except GeneratorExit:
        print("Generator closed")

gen = my_generator()
next(gen)
gen.close()  # Raises GeneratorExit
Enter fullscreen mode Exit fullscreen mode

SystemExit:

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

Example:

import sys

try:
    sys.exit(1)
except SystemExit as e:
    print(f"SystemExit: {e}
Enter fullscreen mode Exit fullscreen mode

")
KeyboardInterrupt:

Explanation: Raised when the user interrupts the program (e.g., by pressing Ctrl+C).

Example:

try:
    while True:
        pass  # Infinite loop
except KeyboardInterrupt:
    print("Program interrupted by the user")
Enter fullscreen mode Exit fullscreen mode

StopIteration:

Explanation: Raised when there are no more items to be returned by an iterator.

Example:

my_iterator = iter([1, 2, 3])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)