Exception Handling
January 14, 2018
Exception Handling
It will be terrible to have a live program that does not have any form of error recovery. Thankfully, Python provides us with a suite of tools to gracefully handle errors without crashing the entire program.
Keywords
Before we can jump into the examples, we will need to understand the Python keywords that perform exception handling.
tryStatements that are likely to result in an exception are placed between
tryandexceptblocks.exceptIf any exception occurs in the
tryblock, code in theexceptblock will be executed. There can be multipleexceptblocks for eachtryblock - this enables the programmer to have specific handlers for different exceptions.elseCode in this block will get executed if no exceptions occur. This block is not mandatory.
finallyLike the keyword suggests, code in this block gets executed post execution of the code in the
try ... exceptblocks. It is key to note that this execution always happens. Due to this property, thefinallyblock is often used for clean-up operations. This block is not mandatory.
The following is a code representation of the text above.
try:
# code that is likely to result in exceptions
pass
except:
# code that handles the exceptions raised
print("exception!")
else:
# code that is executed is no exception is raised
pass
finally:
# code that is executed regardless of what happens in prior blocks
pass
Common Exceptions
We will next cover common issues and the in-built exceptions that Python provides to handle them.
ValueError
A ValueError occurs when a function is applied to an object of an appropriate type, but inappropriate value. For instance, attempting to convert a non-integer string to an integer will throw a ValueError.
try:
int('string')
except ValueError as e:
print(e)
invalid literal for int() with base 10: 'string'
TypeError
A TypeError occurs when a function is applied to an object of an inappropriate type. For instance, trying to sum a string and an integer will throw a TypeError.
try:
'2' + 2
except TypeError as e:
print(e)
must be str, not int
KeyError
A KeyError occurs when the program attempts to access a key that does not exist in the dictionary.
dict = {}
try:
dict['key']
except KeyError as e:
print(e)
'key'
IndexError
An IndexError occurs when the program attempts to access an item in an iterable that is out of range. For instance, attempting to access index 3 in a list of 3 items (Python is zero-based indexing, therefore index 3 does not exist) results in an IndexError.
my_list = ['a', 'b', 'c']
try:
my_list[3]
except IndexError as e:
print(e)
list index out of range