Michael Powe wrote: > On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote: >> Michael Powe wrote: >> >> > I can't work out how to suppress stacktrace printing when exceptions >> > are thrown. >> >> [snip rant] >> >> It might have been a good idea to read a tutorial like >> >> http://docs.python.org/tutorial/errors.html#handling-exceptions > >> or ask before you got annoyed enough to write that rant ;) > > Hello, > > Thanks for the reply. Stupid me, I just read a half dozen articles on > the web about python exception handling, including some at > docs.python. At no point is the 'as' clause discussed as being > required.
>> WRONG: >> >> >>> try: >> ... 1/0 >> ... except ZeroDivisionError("whatever"): >> ... print "caught" >> ... >> Traceback (most recent call last): >> File "<stdin>", line 2, in <module> >> ZeroDivisionError: integer division or modulo by zero >> >> CORRECT: >> >> >>> try: >> ... 1/0 >> ... except ZeroDivisionError as e: >> ... print "caught", e >> ... >> caught integer division or modulo by zero > Note that in section 8.3 of that article, the statement is made that > if the exception matches the the exception type in the following > format, the statements within the except clause are executed. > > except URLError : > # do something > > That in fact, seems to me to be incorrect. It is not my experience > (e.g., print statements are not executed in the example I gave and the > sys.exit() is not called). Sorry, the as-clause is *not* necessary. The relevant difference between the correct and the wrong approach is that you must not instantiate the exception: WRONG: >>> try: ... 1/0 ... except ZeroDivisionError("whatever"): ... print "caught" ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ZeroDivisionError: integer division or modulo by zero CORRECT: >>> try: ... 1/0 ... except ZeroDivisionError: ... print "caught" ... caught I just put in the as-clause to show an easy way to print the exception. I did not anticipate that it would obscure the message. Peter _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor