I’ve read this article http://docs.python.org/2/tutorial/errors.html two times to make sure. It avoids the topic entirely.
- I’ve tried throwing something which is not an
ExceptionorExceptionBase, the interpreter told me I can only throwExceptionBase-esque and old-style classes’ object. - So I tried throwing old-style class’ object:
>>> class Foo():
... pass
...
>>> try:
... raise Foo()
... except Exception as foo:
... print 'foo %s' % foo
... except:
... print 'not an exception'
... else:
... print 'it\'s all good'
...
not an exception
>>>
Surprise… So, how do I catch all of them and examine what was caught?
EDIT:
Motivation.
- Overly defensive coding has never been a bad practice. Suppose I’m writing a deamon program, why wouldn’t I try to prevent as many potential dangers as is possible by doing something that by other standards is trivial?
- Programs don’t always run in a friendly environment, some times other programs try to compromise your program, in which case you do need to prevent all kinds of errors. Some times it makes sense. Think of, for example a CGI implementation – would you like your entire server to go down, if some idiot who rented a piece of it put a script in it, which threw this “unexpected” error?
- Some frameworks already catch all errors for you, so getting your message from under the layers of the framework code isn’t easy. Throwing something that the framework code isn’t catching may be a good strategy to bypass that (this isn’t just a theoretical case, I did that before).
EDIT:
While that feels like it should work, it doesn’t. Here’s a hacky way: