The try is a compound, multipart statement.
It starts with a try header line, followed by a block of indented statements.
Then one or more except clauses that identify exceptions to be caught and blocks to process them.
An optional else clause and block at the end.
try: statements # Run this main action first except name1: statements # Run if name1 is raised during try block except (name2, name3): statements # Run if any of these exceptions occur except name4 as var: statements # Run if name4 is raised, assign instance raised to var except: statements # Run for all other exceptions raised else: statements # Run if no exception was raised during try block
try statement clause forms
Clause form | Interpretation |
---|---|
except: | Catch all (or all other) exception types. |
except name: | Catch a specific exception only. |
except name as value: | Catch the listed exception and assign its instance. |
except (name1, name2): | Catch any of the listed exceptions. |
except (name1, name2) as value: | Catch any listed exception and assign its instance. |
else: | Run if no exceptions are raised in the try block. |
finally: | Always perform this block on exit. |