[Tutor] Exception Handling and Stack traces

Evert Rol evert.rol at gmail.com
Fri Sep 10 16:33:04 CEST 2010


>>> 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.

Because 'as' didn't use to be there. That is more recent.

The real difference is between using an 'instance' and a class in the except clause. You used the former, you need the latter.


> 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).

Have you tried this? In your example, you have 

	except urllib2.URLError("Badly formed URL") :

which is quite a different thing; and I'm quite sure it's like that in the docs.
If you have tried the above ("except URLError"), I'm curious about an example.

Cheers,

  Evert



> 
> I'll follow up on your suggestions.  I appreciate the help.
> 
> Thanks.
> 
> mp
> 
>> To catch an exception you have to put the class into the except clause, not 
>> an instance. Basic example, using 2.6 syntax:
>> 
>> 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
>> 
>> Peter



More information about the Tutor mailing list