Exception specifying 🐍
Story: (You can skip) I wanted to add a testing mode to a program. I wanted the testing mode to return an integer in C style. (0 means a successful termination, while 1 means a "bad" termination.) Problem. I would want to print the error type in case of an error occurred, but I did not want to cause the program to terminate. Question: How can I print the error type without raising the error? The 10 km long ladder of except blocks is not the wanted solution.
6/24/2019 1:36:51 PMSeb TheS
6 AnswersNew Answer
Seb TheS More experiment try: 5/0 // (1) a = "12.13" a += 1 // (2) except Exception as e: print(e.with_traceback(None)) prints only - division with zero for (1) and can only concatenate str (not "int") to str for (2)
Seb TheS Glad to hear your issue is resolved 👍🙂
Seb TheS I tried this import traceback try: i = 5/0 // (1) a = str(12.13) a += 1 // (2) except: // catch all exception print(traceback.format_exc()) And this is what i get for (1) ERROR:root:Traceback (most recent call last): File "<string>", line 5, in <module> ZeroDivisionError: division by zero for (2) after commenting (1) Traceback (most recent call last): File "<string>", line 7, in <module> TypeError: can only concatenate str (not "int") to str I wish there is a way(should be, i have not explored all options and methods available) to get the error without additional details like line no, module etc. Not sure if this is what you are looking for.
maybe something like this ? I believe it works but its extremely bad. def error1(): return 1/0 def error2(): return 1+"1" for i in [error1,1,"Hello,World",error2]: try: print(i())if callable(i)else print(i) except Exception as e: print(e)
If i understood you right, here's what i believe you mean (let me know if you need clarification): import sys try: print(1/0) #or any error except: print(sys.exc_info())
The as keyword is gold. I should have checked dir(Exception), because I did not know anything about with_traceback method. Thank you. I expected something much more complex. The question is answered.