How to catch StandardError Exception in Python?

PythonServer Side ProgrammingProgramming

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
raja
Updated on 12-Feb-2020 10:41:26

Advertisements