The try…except statements
To handle errors (also known as exceptions) in Python, you can use the try…except statements. These statements tell Python what to do when an exception is encountered. This act of detecting and processing an exception is called exception handling. The syntax of the try…except statements is:
try: statements # statements that can raise exceptions except: statements # statements that will be executed to handle exceptions
If an exception occurs, a try block code execution is stopped and an except block code will be executed. If no exception occurs inside the try block, the statements inside the except block will not be executed.
Consider the following example:
age=int(input('Enter your age: ')) if age <= 21: print('You are not allowed to enter, you are too young.') else: print('Welcome, you are old enough.')
The example above asks the user to enter his age. It then checks to see if the user is old enough (older than 21). The code runs fine, as long as user enters only numeric values. However, consider what happens when the user enters a string value:
>>> Enter your age: 13 You are not allowed to enter, you are too young. >>> RESTART >>> Enter your age: 22 Welcome, you are old enough. >>> RESTART >>> Enter your age: a Traceback (most recent call last): File "C:/Python34/Scripts/exceptions.py", line 2, in <module> age=int(input('Enter your age: ')) ValueError: invalid literal for int() with base 10: 'a' >>>
Because a numeric value is expected, the program crashed when the user entered a non-numeric value. We can use the try…except statements to rectify this:
try: age=int(input('Enter your age: ')) except: print('You have entered an invalid value.')
Now, the code inside the try block has its exceptions handled. If the user enters a non-numeric value, the statement inside the except block will be executed:
>>> Enter your age: a You have entered an invalid value. >>>