The difference between the exception: and except for the exception:

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

Can except deal with anything that is no exception?

+6
source share
2 answers

In Python 2.5, there is a new BaseException that serves as the base class for Exception . As a result, something like GeneratorExit , which is inherent directly from BaseException , will depend on except: but not on except Exception:

+6
source

This is from the document.

If an exception occurs that does not match the exception named in except, it is passed to the external try statements; if there is no handler, this is an unhandled exception, and execution stops with 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 an except clause only if you encounter a named error, ValueError

0
source

Source: https://habr.com/ru/post/944647/


All Articles