Daniel
Daniel

Reputation: 1406

Why is it possible in Python to have an except clause for an undefined exception?

My google-fu is failing me. Why does the following program compile and run with no error (Python 2 and 3)?

try:
    print('something')
except ThisNameDoesNotExist:
    print('blah')

I can't think of a good reason why this wouldn't cause an error. I get that it's not executing that except clause, so not hitting the undefined variable, but it seems like it should be fairly easy to catch to me. Can someone explain to me?

Upvotes: 1

Views: 391

Answers (1)

mhlester
mhlester

Reputation: 23231

You do get the error if Python actually evaluates that line. As soon as there is an exception, it sees ThisNameDoesNotExist does not exist:

>>> try:
...     print(1/0)
... except ThisNameDoesNotExist:
...     print('blah')
... 
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
NameError: name 'ThisNameDoesNotExist' is not defined

Otherwise, there is no error, as is the nature of the Python.

Upvotes: 2

Related Questions