Thursday, 15 January 2015

python - ValueError vs acessing sys.exc_info() -



python - ValueError vs acessing sys.exc_info() -

why "class 'attributeerror'" can not accessed via valueerror, or there way of not aware?

i need phone call sys.exec_info() did in code below access info wrong calling of attribute of method of class valueerror in not capable of providing information.

just explain myself bit farther - have encountered situation when list of methods conditional on properties of instance created using class (as instance's methods), having easy , standard handle error caused improper calling of instance's method or property efficient way sold forks in code , save memory on unused methods , properties if creating 'unified' instances.

i set in code below demonstrate wrong attribute calling same applies methods.

#!/usr/bin/python3 import sys class number(): def __init__(self, real, im=0): if im == 0: self.real=real else: self.real=real self.im=im x=number(10) '''#this part not work try: print(' x = ', x.real, " + ", x.im, 'i') except valueerror err: print(err) ''' try: print(' x = ', x.real, " + ", x.im, 'i') except: print(sys.exc_info()[0])

attributeerror not subclass of valueerror, former not caught when handling latter.

catch both if need handle both exceptions:

try: print(' x = ', x.real, " + ", x.im, 'i') except (attributeerror, valueerror) exc: print(exc)

or grab attributeerror:

try: print(' x = ', x.real, " + ", x.im, 'i') except attributeerror exc: print(exc)

if wanted grab (almost) exceptions, grab exception:

except exception exc:

but careful blanket, pokemon exception handling.

python

No comments:

Post a Comment