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



StandardError in Python 2

In Python 2, StandardError was a built-in exception class that is 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.

Example

Following is a basic example of raising 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:', ZeroDivisionError('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.

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)

We get the output as shown below -

Caught an exception: invalid literal for int() with base 10: 'abc'
Updated on: 2025-06-07T17:48:24+05:30

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements