Exception specifying 🐍 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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.

24th Jun 2019, 1:36 PM
Seb TheS
Seb TheS - avatar
3 Answers
+ 3
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)
24th Jun 2019, 3:57 PM
Choe
Choe - avatar
+ 2
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()[1])
24th Jun 2019, 2:15 PM
Mo Hani
Mo Hani - avatar
+ 2
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.
24th Jun 2019, 3:57 PM
Seb TheS
Seb TheS - avatar