I've read many questions and articles on exception handling in Python (and in general), but I still think that it's the most confusing thing ever. I ended up doing something like this:
# error class for exceptions specific to this script class MyError(Exception): pass # error class for exceptions in MyClass, # which can be used from outside of this script class MyClassError(Exception): pass class MyClass: ... # class has method that takes a function as a parameter def method(self, param_function): ... param_function(a, b, c, d) try: some_other_funtion(arg) except ValueError, e: raise MyClassError("Some message") ... # outside of MyClass if __name__ == "__main__": # read input from console etc. # ... def function(a, b, c, d): # .... try: # something with a except ValueError, e: raise MyError("My message:" + a) try: # something with b except ValueError, e: raise MyError("My message:" + b) try: # something with c except ValueError, e: raise MyError("My message:" + c) try: # something with d except ValueError, e: raise My Error("My slightly different message:" + d) x = MyClass() try: x.method(function) except (IOError, MyError, MyClassError) as e: print e
I want the user of the script to just get a user-friendly message if the error is a result of him passing the wrong input.
The messages with which I raise my custom exceptions are user-friendly, and they (in my opinion) contain all the information I want the user to see.
That's also the reason why I'm handling IOError in a similar manner. I expect an IOError only if the user provides a wrong filename, and I want him to see something like "File not found: name of the file" and nothing more.
Why this seems wrong:
In my main function, in
function, I'm basically surrounding every line of code with a try-catch, and handling every exception in a similar manner - sometimes the message the user should see is a little different, but mostly the only difference is the parameter in the message.
Am I handling my exceptions in the right places?
Am I handling them in the right way?
Is the code duplication that I'm doing in