All the IPython Notebooks in Python Files lecture series by Dr. Milaan Parmar are available @ GitHub
In this class, you will learn about different types of errors and exceptions that are built-in to Python. They are raised whenever the Python interpreter encounters errors.
We can make certain mistakes while writing a program that lead to errors when we try to run it. A python program terminates as soon as it encounters an unhandled error. These errors can be broadly classified into two classes:
Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.
# Example 1:
if a < 3
File "<ipython-input-1-a8dfd56d4d8e>", line 3 if a < 3 ^ SyntaxError: invalid syntax
Exaplanation:
As shown in the example, an arrow indicates where the parser ran into the syntax error.
We can notice here that a colon :
is missing in the if
statement.
# Example 2:
print 'hello world'
File "<ipython-input-3-cb8ac02fbcd3>", line 3 print 'hello world' ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
Exaplanation:
As you can see we made a syntax error because we forgot to enclose the string with parenthesis ()
and Python already suggests the solution. Let us fix it.
Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.
For instance, they occur when we try to open a file(for reading) that does not exist (FileNotFoundError
), try to divide a number by zero (ZeroDivisionError
), or try to import a module that does not exist (ImportError
).
Whenever these types of runtime errors occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred.
Let's look at how Python treats these errors:
# Example 1: ZeroDivisionError
1 / 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-4-9b9247988596> in <module> 1 # Example 1: ZeroDivisionError 2 ----> 3 1 / 0 ZeroDivisionError: division by zero
# Example 2: FileNotFoundError
open("imaginary.txt")
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-5-6ac8e81b6f0c> in <module> 1 # Example 2: FileNotFoundError 2 ----> 3 open("imaginary.txt") FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
# Example 3: ImportError
from math import power
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-6-0ef33cc3a94d> in <module> 1 # Example 3: ImportError 2 ----> 3 from math import power ImportError: cannot import name 'power' from 'math' (unknown location)
Exaplanation:
There is no function called power
in the math
module, it goes with a different name: pow
.
We debugged the error by defining the variable name.
# Example 1:
print(age)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-7-119e50d96cfb> in <module> 1 # Example 1: 2 ----> 3 print(age) NameError: name 'age' is not defined
Exaplanation:
As you can see from the message above, name age
is not defined. Yes, it is true that we did not define an age
variable but we were trying to print it out as if we had had declared it. Now, lets fix this by declaring it and assigning with a value.
We debugged the error by defining the variable name.
# Example 1:
numbers = [1, 2, 3, 4, 5]
numbers[5]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-8-c00e5d7d3c3e> in <module> 2 3 numbers = [1, 2, 3, 4, 5] ----> 4 numbers[5] IndexError: list index out of range
Exaplanation:
In the example above, Python raised an IndexError
, because the list has only indexes from 0 to 4 , so it was out of range.
# Example 1:
import maths
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-9-e2e604bf92de> in <module> 1 # Example 1: 2 ----> 3 import maths ModuleNotFoundError: No module named 'maths'
Exaplanation:
In the example above, I added an extra s
to math deliberately and ModuleNotFoundError
was raised. Lets fix it by removing the extra s
from math.
# Example 1:
import math
math.PI
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-10-df6ce7ede1dc> in <module> 2 3 import math ----> 4 math.PI AttributeError: module 'math' has no attribute 'PI'
Exaplanation:
As you can see, I made a mistake again! Instead of pi
, I tried to call a PI
function from math
module. It raised an AttributeError
, it means, that the function does not exist in the module. Lets fix it by changing from PI
to pi
.
# Example 1:
users = {'name':'Milaan', 'age':96, 'country':'England'}
users['name']
'Milaan'
users['county']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-12-fbf7cddd4b2a> in <module> ----> 1 users['county'] KeyError: 'county'
Exaplanation:
As you can see, there was a typo in the key used to get the dictionary value. so, this is a KeyError
and the fix is quite straight forward. Let's do this!
# Example 1:
6 + '3'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-13-f7ffd6347533> in <module> 1 # Example 1: 2 ----> 3 6 + '3' TypeError: unsupported operand type(s) for +: 'int' and 'str'
Exaplanation:
In the example above, a TypeError
is raised because we cannot add a number to a string. First solution would be to convert the string to int or float. Another solution would be converting the number to a string (the result then would be '63'). Let us follow the first fix.
# Example 1:
int('19a')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-ee4e8ee8c904> in <module> 1 # Example 1: 2 ----> 3 int('19a') ValueError: invalid literal for int() with base 10: '19a'
Exaplanation:
In this case we cannot change the given string to a number, because of the a
letter in it.
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local()
function as follows:
print(dir(locals()['__builtins__']))
locals()['__builtins__']
will return a module of built-in exceptions, functions, and attributes. dir
allows us to list these attributes as strings.
Some of the common built-in exceptions in Python programming along with the error that cause them are listed below:
Exception | Cause of Error |
---|---|
AssertionError |
Raised when an assert statement fails. |
AttributeError |
Raised when attribute assignment or reference fails. |
EOFError |
Raised when the input() function hits end-of-file condition. |
FloatingPointError |
Raised when a floating point operation fails. |
GeneratorExit |
Raise when a generator's close() method is called. |
ImportError |
Raised when the imported module is not found. |
IndexError |
Raised when the index of a sequence is out of range. |
KeyError |
Raised when a key is not found in a dictionary. |
KeyboardInterrupt |
Raised when the user hits the interrupt key (Ctrl+C or Delete ). |
MemoryError |
Raised when an operation runs out of memory. |
NameError |
Raised when a variable is not found in local or global scope. |
NotImplementedError |
Raised by abstract methods. |
OSError |
Raised when system operation causes system related error. |
OverflowError |
Raised when the result of an arithmetic operation is too large to be represented. |
ReferenceError |
Raised when a weak reference proxy is used to access a garbage collected referent. |
RuntimeError |
Raised when an error does not fall under any other category. |
StopIteration |
Raised by next() function to indicate that there is no further item to be returned by iterator. |
SyntaxError |
Raised by parser when syntax error is encountered. |
IndentationError |
Raised when there is incorrect indentation. |
TabError |
Raised when indentation consists of inconsistent tabs and spaces. |
SystemError |
Raised when interpreter detects internal error. |
SystemExit |
Raised by sys.exit() function. |
TypeError |
Raised when a function or operation is applied to an object of incorrect type. |
UnboundLocalError |
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
UnicodeError |
Raised when a Unicode-related encoding or decoding error occurs. |
UnicodeEncodeError |
Raised when a Unicode-related error occurs during encoding. |
UnicodeDecodeError |
Raised when a Unicode-related error occurs during decoding. |
UnicodeTranslateError |
Raised when a Unicode-related error occurs during translating. |
ValueError |
Raised when a function gets an argument of correct type but improper value. |
ZeroDivisionError |
Raised when the second operand of division or modulo operation is zero. |
If required, we can also define our own exceptions in Python. To learn more about them, visit Python User-defined Exceptions.
We can handle these built-in and user-defined exceptions in Python using try
, except
and finally
statements. To learn more about them, visit Python try, except and finally statements.