On Thu, Jun 4, 2015 at 2:15 AM, Cecil Westerhof <ce...@decebal.nl> wrote: >> And I'd also skip the bare except clause. If you get any sort of >> exception, whether it's a bug, a failure from libturpial, a network >> error, or anything else, your code will just terminate with a bland >> and useless message. Much better to simply let the exception bubble >> up. > > I kept the except. I like to see the message that went wrong. ;-)
In that case, there's an easier way to deal with it: just raise a different exception, and let them chain. Something like this: >>> def send_message(msg): ... try: 1/0 ... except: raise FailedMessageException(msg) ... >>> class FailedMessageException(Exception): pass ... >>> send_message("Test") Traceback (most recent call last): File "<stdin>", line 2, in send_message ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in send_message __main__.FailedMessageException: Test But I'd still avoid the bare except, and use "except Exception:" instead. I don't think you want to catch SystemExit in this way, for instance. So here's how I'd write that code: >>> def send_message(msg): ... try: 1/0 ... except Exception as e: raise FailedMessageException(msg) from e ... >>> send_message("Test") Traceback (most recent call last): File "<stdin>", line 2, in send_message ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in send_message __main__.FailedMessageException: Test (Also, the use of "from" here causes a slightly different wording, which I think is more appropriate. But that's minor.) You get the report of which message failed, plus you get the complete traceback from the original exception. Much MUCH more useful. ChrisA -- https://mail.python.org/mailman/listinfo/python-list