Youcha
Youcha

Reputation: 1564

Difference between except: and except Exception:

Is there any difference between except: and except Exception: ?

Can except deal with anything that is not an exception?

Upvotes: 6

Views: 306

Answers (2)

kiriloff
kiriloff

Reputation: 26333

This is from the doc

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

You can even be more specific.

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."

Here, you enter except clause only if you are facing the named error, ValueError

Upvotes: -1

marcoseu
marcoseu

Reputation: 3952

As of Python 2.5, there is a new BaseException which serve as base class for Exception. As result, something like GeneratorExit that inherents directly from BaseException would be caught by except: but not by except Exception:.

Upvotes: 6

Related Questions