CNK
CNK

Reputation: 1063

listing exceptions programmatically - Python

Is there any way to programmatically determine which exceptions an object or method might raise?

Like dir(obj) lists available methods, I'm looking for the equivalent dir_exceptions(obj).

As far as I know, the only way to achieve this would be to parse the source.

Upvotes: 0

Views: 210

Answers (4)

jaime
jaime

Reputation: 2344

No, there is not a practical way to do this.

Most python developers derive from Exception, so if you're not sure, just catch Exception.

try:
    some_secret_code()
except Exception:
    print 'oops, something happened'

If you're thinking that you can import a module and poke around looking for things derived from Exception, that won't quite work either. What about that python nut that does this ->

exec "raise SystemExit()"

I'm not sure that there is a non-practical way to accomplish this.

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114035

I don't think this is possible either, but if you trust that the programmer has named their exceptions with "Exception" or "Error" in the name, then you could do a dir on the class and search for elements that end with "Exception" or "Error". Aside from that (which is pretty hacky in itself), I don't see a straightforward/native/idiomatic way to do this

Upvotes: -1

Matt Fenwick
Matt Fenwick

Reputation: 49105

It looks like you'll have to trust the code's developers on this one: if they did a good job, the method/class documentation should list all the exceptions that could be raised.

Upvotes: 2

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72845

I don't think this is possible. An exception is a runtime phenomenon and you'll know what it possible (or what happens) only while running. Why would you want to do this though?

Upvotes: 2

Related Questions