Explanation of except ... as : - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Explanation of except ... as : (/thread-32498.html) |
Explanation of except ... as : - Fernando_7obink - Feb-13-2021 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 ein 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 respectively....doesnt mean if we try to print(object)will give us an sort of output like this
RE: Explanation of except ... as : - bowlofred - Feb-13-2021 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.
RE: Explanation of except ... as : - deanhystad - Feb-13-2021 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) 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.
|