try: if 0 <= index < len(my_list): value = my_list[index] value = my_list[index] except IndexError: else: value = -1 value = -1 Example 3: When you can just as easily test to see if the key is valid doing this: DON’T DO THIS: try: if key in my_dictionary.keys(): value = my_dictionary[key] value = my_dictionary[key] except KeyError: else: value = -1 value = -1 Principle 2: If you call a function that potentially raises exceptions, and you can do something appropriate to deal with the exception, then surround the code that contains the function call with a block. try: except: Principle 3: If you call a function that potentially raises exceptions, and you can’t do anything meaningful about the conditions that are raised, then don’t catch the exception. Try with finally If you have code that you want to be executed even if exceptions occur, you can include a finally code block: try: # Your normal code goes here. # Your code might include function calls which might raise exceptions. # If an exception is raised, some of these statements might not be executed. finally:
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 Principle 2: If you call a function that potentially raises exceptions, and you can do something appropriate to deal with the exception, then surround the code that contains the function call with a try: except: block. Principle 3: If you call a function that potentially raises exceptions, and you can’t do anything meaningful about the conditions that are raised, then don’t catch the exception. Try with finally If you have code that you want to be executed even if exceptions occur, you can include a finally code block: try: # Your normal code goes here. # Your code might include function calls which might raise exceptions. # If an exception is raised, some of these statements might not be executed. finally: