+ 1

Python exception handling best practice?

I like to prepare a boilerplate code for exception handling that I can routinely use with shortcuts in my IDE. I have made this code below as a first attempt. Is it OK for general purposes? Any suggestion for improvement? try: # actual code comes here: pass # can multiplied for other types of known exceptions: except IndexError as err: print("IndexError: {0}".format(err)) exit(1) # for unexpected errors: except Exception as inst: print(type(inst)) # the exception instance print(inst.args) # arguments stored in .args print(inst) # __str__ allows args to be printed directly exit(2)

9th Mar 2020, 10:03 AM
Prof. Dr. Zoltán Vass
3 Respostas
+ 4
Prof. Dr. Zoltán Vass, I used my sample in a previous answer, where the question about raising user exceptions has been coming up.
9th Mar 2020, 12:05 PM
Lothar
Lothar - avatar
+ 3
I like and use this very basic approach: https://code.sololearn.com/cPgiDJLNwaQW/?ref=app
9th Mar 2020, 10:54 AM
Lothar
Lothar - avatar
+ 1
Lothar Thanks for your suggestion. I also prefer simplicity. In your code, why did you include the line below? “raise Exception # not needed”
9th Mar 2020, 11:12 AM
Prof. Dr. Zoltán Vass