How to catch StandardError Exception in Python?\\\


There is the Exception class, which is the base class for StopIteration, StandardError and Warning. All the standard errors are derived from StandardError. Some standard errors like ArithmeticErrror, AttributeError, AssertionError are derived from base class StandardError.

When an attribute reference or assignment fails, AttributeError is raised. For example, when trying to reference an attribute that does not exist:

We rewrite the given code and catch the exception and know it type.

Example

import sys
try:
class Foobar:
def __init__(self):
self.p = 0
f = Foobar()
print(f.p)
print(f.q)
except Exception as e:
print e
print sys.exc_type
print 'This is an example of StandardError exception'

Output

0
Foobar instance has no attribute 'q'
<type 'exceptions.AttributeError'>
This is an example of StandardError exception

Updated on: 12-Feb-2020

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements