-1

Why "class 'AttributeError'" can not be accessed via ValueError, or there is really a way to do it of which I am not aware?

I need to call sys.exec_info() as I did in the code below to access information about incorrect calling of an attribute of a method of a class but ValueError in itself is not capable of providing this information.

Just to explain myself a bit further - I have encountered a situation when list of methods is conditional on the properties of an instance created using the class (as well as the instance's methods), so having an easy and standard handle to the error caused by improper calling of an instance's method or a property would be really efficient way to sold some forks in the code and to save memory on unused methods and properties if creating 'unified' instances.

I put in a code below to demonstrate incorrect attribute calling but the same applies to the 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 does not work
try:
    print(' x = ', x.real, " + ", x.im, 'i')
except ValueError as err:
    print(err)
'''
try:
    print(' x = ', x.real, " + ", x.im, 'i')
except:
    print(sys.exc_info()[0])
VDV
  • 874
  • 9
  • 12

1 Answers1

1

AttributeError is not a subclass of ValueError, so the former is not caught when you are only handling the latter.

Catch both if you need to handle both exceptions:

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

or just catch AttributeError:

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

If you wanted to catch (almost) all exceptions, catch Exception:

except Exception as exc:

but be careful with blanket, Pokemon exception handling.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343