13.6. Principles for using Exceptions

There are many bad examples of exception use on the Internet. The purpose of an exception is to modify the flow-of-control, not to catch simple errors. If your try: except: block is in the same function that raises the exception, you are probably mis-using exceptions.

Example 1:

DON’T DO THIS:

When you can just as easily test for no items in the list doing this:

try:
  average = sum(a_list) / len(a_list)
except ZeroDivisionError:
  average = 0
if len(a_list) > 0:
  average = sum(a_list) / len(a_list)
else:
  average = 0

Example 2:

DON’T DO THIS:

When you can just as easily test for a valid index doing this:

try:
  value = my_list[index]
except IndexError:
  value = -1
if 0 <= index < len(my_list):
  value = my_list[index]
else:
  value = -1

Example 3:

DON’T DO THIS:

When you can just as easily test to see if the key is valid doing this:

try:
  value = my_dictionary[key]
except KeyError:
  value = -1
if key in my_dictionary.keys():
  value = my_dictionary[key]
else:
  value = -1

Example: Suppose you have a function that reads a file to set the state of an application when it starts up. You should catch any errors related to reading the file and set the state of the application to default values if they can’t be set from the file.

try:
  load_state('previous_state.txt')
except OSError:
  set_state_to_defaults()
You have attempted of activities on this page