Catch specific exceptions

We’ve already mentioned that catching all exceptions with the except clause and handling every case in the same way is not considered to be a good programming practice. It is recommended to specify an exact exceptions that the except clause will catch. For example, to catch an exception that occurs when the user enters a non-numerical value instead of a number, we can catch only the built-in ValueError exception that will handle such event.

Here is an example:

try:
    age = int(input('Enter your age: '))
except ValueError:
    print('Invalid value entered.')
else:
    if age >= 21:
        print('Welcome, you are old enough.')
    else:
        print('Go away, you are too young.')

The code above will ask the user for his age. If the user enters a number, the program will evaluate whether the user is old enough. If the user enters a non-numeric value, the Invalid value entered message will be printed:

>>> 
Enter your age: 5
Go away, you are too young.
>>>RESTART
>>> 
Enter your age: 22
Welcome, you are old enough.
>>>RESTART
>>> 
Enter your age: a
Invalid value entered.
>>>

In the output above, you can see that the statements inside the else clause were executed when the user entered a number. However, when the user entered a non-numeric value (the letter a), the ValueError exception occurred and the print statement inside the except ValueError clause was executed.

Note that the except ValueError clause will catch only exceptions that occur when the user enters a non-numeric value. If another exception occur, such as the KeyboardInterrupt exception (raised when the user hits Ctrl+c), the except ValueError block would not handle it. You can, however, specify multiple except clauses to handle multiple exceptions, like in this example:

try:
    age = int(input('Enter your age: '))
except ValueError:
    print('Invalid value entered.')
except KeyboardInterrupt:
    print('You have interrupted the program.')    
else:
    if age >= 21:
        print('Welcome, you are old enough.')
    else:
        print('Go away, you are too young.')

The output:

>>> 
Enter your age: 5
Go away, you are too young.
>>> RESTART
>>> 
Enter your age: 22
Welcome, you are old enough.
>>>RESTART
>>> 
Enter your age: a
Invalid value entered.
>>>
>>> 
Enter your age: 
You have interrupted the program.
>>>

You can also handle multiple exceptions with a single except clause. We can simple rewrite our program like this:

try:
    age = int(input('Enter your age: '))
except (ValueError, KeyboardInterrupt):
    print('There was an exception.')
else:
    if age >= 21:
        print('Welcome, you are old enough.')
    else:
        print('Go away, you are too young.')

To see the full list of exceptions, go here.

Geek University 2022