PythonError Handling
Thetry
block lets you test a block of code for errors.
Theexcept
block lets you handle the error.
Thefinally
block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using thetry
statement:
Example
Thetry
block will generate an exception, becausex
is not defined:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error: