Anurag Uniyal
Anurag Uniyal

Reputation: 88777

How to catch str exception?

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

Upvotes: 2

Views: 3092

Answers (4)

Anurag Uniyal
Anurag Uniyal

Reputation: 88777

Here is the solution from python mailing list, not very elegant but will work if can't avoid the need for such hack

import sys
try:
     raise "a string exception"
except:
     e, t, tb = sys.exc_info()
     if not isinstance(e, str):
          raise    
     print "caught", e

Upvotes: 4

lvh
lvh

Reputation: 760

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

Upvotes: 2

pts
pts

Reputation: 87291

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

Upvotes: 6

Jochen Ritzel
Jochen Ritzel

Reputation: 107648

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.

Upvotes: 2

Related Questions