Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch StandardError Exception in Python?

In following code, I get an error

   class Foobar:
       def __init__(self):
          self.p = 0
    f = Foobar()
    print(f.p)
    print(f.q)

How can I catch this exception and know its type?


1 Answer
Rajendra Dharmkar

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.

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.