How to catch StandardError Exception in Python?\\\\\\\\n

In Python 2, StandardError was a built-in exception class that served as a base class for all built-in exceptions except for SystemExit, KeyboardInterrupt, and GeneratorExit. Using this class, we were able to catch the most common runtime errors in a single except block.

However, since Python 3, the StandardError class has been deprecated, and now all built-in exceptions directly inherit from the Exception class. If you are using Python 3, you should catch exceptions using Exception instead of StandardError.

StandardError in Python 2

The StandardError class in Python 2 was designed to catch all standard exceptions that could occur during normal program execution, excluding system-level interruptions.

Example

Following is a basic example of catching the StandardError exception in Python 2 ?

try:
    value = 10 / 0
except StandardError as e:
    print("Caught an error:", e)

Following is the output obtained ?

Caught an error: integer division or modulo by zero

This example works in Python 2. However, running this code in Python 3 will raise a NameError because StandardError no longer exists.

Python 3 Alternative: Exception Class

In Python 3, we need to use the Exception class instead of StandardError to catch most runtime errors. The Exception class serves the same purpose as StandardError did in Python 2.

Example

In this example, we are catching standard exceptions in Python 3 version ?

try:
    value = int('abc')  # This will raise ValueError
except Exception as e:
    print("Caught an exception:", e)

The output of the above code is ?

Caught an exception: invalid literal for int() with base 10: 'abc'

Example

Here's another example demonstrating exception handling in Python 3 ?

try:
    result = 10 / 0
except Exception as e:
    print("Caught an exception:", e)
    print("Exception type:", type(e).__name__)

The output of the above code is ?

Caught an exception: division by zero
Exception type: ZeroDivisionError

Conclusion

While StandardError was useful in Python 2 for catching common runtime exceptions, Python 3 developers should use the Exception class instead. This change provides the same functionality while maintaining consistency with Python 3's simplified exception hierarchy.

Updated on: 2026-03-13T17:45:54+05:30

609 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements