Let us explore error and exception handling in Python
- Handling Exceptions (try/catch)
- Raising Exceptions
- Cleanup actions (finally)
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:
while True print('Hello world')
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:
Handling Exceptions (try/catch)
It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using
Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the
Flow of try/catch execution
- First, the try clause (the statement(s) between the
exceptkeywords) is executed.
- If no exception occurs, the except clause is skipped and execution of the
trystatement is finished.
- If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the
exceptkeyword, the except clause is executed, and then execution continues after the
- If an exception occurs which does not match the exception named in the except clause, it is passed on to outer
trystatements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
trystatement may have more than one except clause, to specify handlers for different exceptions
- An except clause may name multiple exceptions as a parenthesized tuple as shown above
raise statement allows the programmer to force a specified exception to occur. For example:
try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances
- A finally clause is always executed before leaving the
trystatement, whether an exception has occurred or not.
- When an exception has occurred in the
tryclause and has not been handled by an
exceptclause (or it has occurred in an
elseclause), it is re-raised after the
finallyclause has been executed.
finallyclause is also executed “on the way out” when any other clause of the
trystatement is left via a