views:

178

answers:

4
import sys
try:
    raise "xxx"
except str,e:
    print "1",e
except:
    print "2",sys.exc_type,sys.exc_value

In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad.

except str,e: doesn't catch it? why?

system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2

+2  A: 
try:
    raise "xxx"

except "xxx":
    print "xxx caught"

except <class> only works with classes that are a subclass of Exception i think. Oh btw, use basestring when checking the type of strings, works with unicode strings too.

THC4k
basestring suggestion is a good one in general, thanks
Anurag Uniyal
i can't catch "xxx" because I don't know what the exception from 3rd party lib will be in real code
Anurag Uniyal
+5  A: 

The generic except: clause is the only way to catch all str exceptions.

str exceptions are a legacy Python feature. In new code you should use raise Exception("xxx") or raise your own Exception subclass, or assert 0, "xxx".

pts
+1: Never use string exceptions. Never.
S.Lott
but what can you do about third part library?
Anurag Uniyal
Find a better 3rd-party library. OR. Fix it. You have the source. You can change the source. Just fix it.
S.Lott
+2  A: 

Raising raw strings is just wrong. It's a deprecated feature (and as such should have raised warnings). Catching the explicit string will work if you really need it, and so will catching everything. Since catching everything puts the ugliness in your code, I recommend catching the string explicitly, or even better: fixing the broken library.

try:
    #code_that_throws_string()
    raise("spam")
except "spam":
    pass

The pass statement will be reached. There are loads of good reasons not to use strings as exceptions, and this is one of them (the other being: I don't believe you can get tracebacks, so they're largely useless for bug fixing).

So, fix the library (good). Or catch the string explicitly (bad). Or catch everything (very bad) and do some isinstance(e, str) checking (even worse).

lvh
A: 

ok i found the solution(python mailing list),

not very elegant but will work

import sys
try:
     raise "abc"
except:
     e, t, tb = sys.exc_info()
     if not isinstance(e, str):
          raise    
     print "caught", e
Anurag Uniyal