6

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

Can except deal with anything that is not an exception?

2
  • No, they are functionally identical :-) Commented May 9, 2013 at 16:20
  • Actually, I take that back -- they are different Commented May 9, 2013 at 16:22

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for mentioning BaseException. One important thing that except: catches that except Exception: does not is KeyboardInterrupt. Liberal use of bare except: may make it hard to stop your scripts!
That is correct. KeyboardInterrupt also inherits from BaseException.
SystemExit also inherits from BaseExcrption
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.