Python Forum

Full Version: Explanation of except ... as :
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, i trying to figure out how the except work is...
in this python code
try:
    raise Exception("a", "b")
except Exception as e:
    print(e)
    print(e.__str__())
    print(e.args)
keyword
as e
in here mean the "e" will catch/cover the Exception class isn't it ? so does it mean the "e" variable will become an object like this ?
e = Exception("a", "b")
so how could the
print(e)
print(e.__str__())
print(e.args)
give an output
Output:
a a ('a',)
respectively....doesnt mean if we try to
print(object)
will give us an sort of output like this
Output:
<__main__.e object at 0x0000016BF4C0F880>
When you print() an object, it will generally look for a __str__() method of that object. You should only get a print of the object's address for objects that don't have a __str__ method, or in its absence, a __repr__ method.

If you make your own class and don't provide either method, you'll get that odd default string.

Exception objects have a __str__ method, so that is what is printed. For them, it prints out the passed in information.
print() should only print things like this "<__main__.e object at 0x0000016BF4C0F880>" if the thing being printed does not have a more natural string representation. In Python everything is an object, even numbers. You would be very disappointed if this happened.
x = 3+5
print(x)
Output:
<int object at x0000016BF4C0F880>
If you write classes that have a reasonable string representation you should write dunder methods __str__ and/or __repr__ so you can get better information displayed from a print.