Error Handling in Python

In Python, the try and except blocks are used for error handling, allowing you to catch and handle exceptions (errors) that may occur during the execution of your code.

Here's how the try and except blocks work in Python:

try:
    # Code that may raise an exception
    result = 5 / 0  # This will raise an exception
except Exception as e:
    # Code to handle other exceptions
    print(f"An error occurred: {e}")

In this example, the try block contains the code that might raise an exception. The except block catches and handles exceptions. The Exception class is a built-in Python class that serves as a base class for all exceptions. By specifying Exception, you are catching any exception that inherits from the Exception class.

The output of the above code is as follows:

An error occurred: division by zero

Handling Multiple Exceptions

A try statement may have multiple except blocks for handling different exceptions. The code inside the first matching except block is executed.

Example:

try:
    # Code that may raise an exception
    result = 5 / 0  # This will raise an exception
except ZeroDivisionError:
    # Code to handle the specific exception
    print("Error: Division by zero")
except Exception as e:
    # Code to handle other exceptions
    print(f"An error occurred: {e}")
else:
    # Optional block for code that should run when no exceptions are raised
    print("No exceptions occurred.")

Output:

Error: Division by zero

Python Built-in Exceptions

The table below displays a list of built-in exceptions in Python:

Exception
Cause of Error
ArithmeticError
Raised when an arithmetic operation fails.
AssertionError
Raised when an assert statement fails.
AttributeError
Raised when an attribute referrence or assignment fails.
EOFError
Raised when the built-in function input() or raw_input() hits end-of-file condition.
FloatingPointError
Raised when a floating-point operation fails.
GeneratorExit
Raised when a generator or coroutine is closed.
ImportError
Raised when an import fails.
IndexError
Raised when an trying to access index that is out of range.
KeyError
Raised when trying to read a mapping key that does not exists in a set of existings keys.
KeyboardInterrupt
Raised when a user presses the interrupt key (Crtl+C or Delete).
MemoryError
Raised when the program runs out of memory.
NameError
Raised when a variable is not found in global or local scope.
NotImplementedError
Raised when overriding the abstract methods in a user-defined class.
OSError
Raised due to system-related error return by system functions.
OverflowError
Raised when the result of an arithmetic operation is too big.
ReferenceError
Raised when a weak reference proxy is used to access the referent after the garbage collection.
RuntimeError
Raised when an unspecified error occurs.
StopIteration
Raised when an the built-in next() function is called to indicate that no item is left to be return by an iterator.
SyntaxError
Raised when there is a syntax error.
IndentationError
Raised due to incorrect identation in the code.
TabError
Raised due to incorrect number of tabs and spaces.
SystemError
Raised due to internal error in the Python interpreter.
SystemExit
Raised when the sys.exit() function is called.
TypeError
Raised due to inappropriate argument type.
UnboundLocalError
Raised when a reference is made to a local variable that has not been assigned any value inside a method or function.
UnicodeError
Raised when a Unicode related error occurs.
UnicodeEncodeError
Raised when a Unicode encoding error occurs.
UnicodeDecodeError
Raised when a Unicode decoding error occurs.
UnicodeTranslateError
Raised when a Unicode-related error occurs during translation.
ValueError
Raised when an argument of a function receives the value of another incorrect type.
ZeroDivisionError
Raised when trying to divide a value by 0