Python Built-in Exceptions and Errors

In this Python article, we will discuss some of the most common and frequently occurring exceptions that may arise in Python along with their reasons and corrections with some suitable examples.

1. What is an Exception in Python?

While writing a certain program we might make some mistakes that are thrown as an error during the program execution. These errors can be of two types

  • Syntax errors
  • Runtime errors/exceptions

Ok I get this, but what exactly is an exception?

Exceptions can be defined as an output event raised when there is an error during the execution of a program. In short, when the python script encounters an unmanageable condition, an exception is raised. Exception serves as an object to identify an error.

When we encounter an exception, either we handle the exception using try and except blocks(exception handling) or the program terminates abruptly.

Modern and advanced IDE can identify the syntax error while writing the code so we generally do not end up with syntax errors during the program execution. It might still happen if we are using some normal text editor to write a program.


2. Common Exceptions in Python

Here is the list of some common exception which can be encountered in Python.

Sr.No.Exception Name & Description
1ArithmeticError
This is the base class for every error that occurs while performing numeric computation.
2AssertionError
This error occurs while asserting statement fails.
3AttributeError
This error occurs when there is an assignment failure for a particular attribute.
4Exception
This is the base class for every exception in python.
5EOFError
This error occurs if input() or raw_input() encounters no input and file has ended.
6EnvironmentError
If any exception occurs out of the environment of python then this error occurs.
7FloatingPointError
This error occurs when float calculation fails.
8ImportError
This error occurs when the import of any file fails.
9IndexError
Raised when an index is not found in a sequence.
10IndentationError
Raised when indentation is not specified properly.
11IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
12KeyboardInterrupt
This error occurs when ctrl+c is pressed which Raised when there is a break in program execution.
13KeyError
This error occurs if a particular key in the dictionary is found absent.
14LookupError
This is a class of errors that occurs if there are any lookup errors.
15NameError
This error occurs if, in the given namespace, the identifier is found absent.
16NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
17OverflowError
This error occurs when the computation has reached the highest limit for a particular numeric type.
18RuntimeError
This error occurs when the occurred error is not under any given category.
19StopIteration
Raised when the next() method of an iterator does not point to any object
20SystemExit
This error occurs by the function sys.exit()
21StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
22SystemError
This error occurs when there is any internal problem. However, encountering of such error does not make interpreter to exit the program.
23SyntaxError
This error occurs if there is any syntax error.
24TypeError
This error occurs when the specified data type is not valid to perform operation or function.
25UnboundLocalError
This error occurs when value is not assigned to a local variable or function and still we try to access it.
26ValueError
This error occurs if the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
27ZeroDivisionError
This error occurs when a nmeric type is divided by zero.
List of commonly raised exception error

Let’s implement some of them using certain examples.

2.1. IndexError

This exception is raised when an index is not found in a sequence.

list_data = [2,4,6,8]
x = list_data[5]
Output
Traceback (most recent call last):
File "xyz.py", line 2, in 
list_data[5]
IndexError: list index out of range

2.2. ModuleNotFoundError

This error occurs when we make an import for a module and the module can not be found.

import some_xyz_module
list_data=[2,4,6,8]
x=list_data[3]
Output
Traceback (most recent call last): 
File "xyz.py", line 1, in <module>              
import some_xyz_module ModuleNotFoundError: No module named 'some_xyz_module'

2.3. KeyError

This error occurs if a particular key in the dictionary is found absent.

dict_data={'2':"two", '4':"four", '6':"six"}
dict_data['8']
Output
Traceback (most recent call last): 
File "abc.py", line 1, in <module>              
dict_data['8'] KeyError: '8'

2.4. StopIteration

Raised when the next() method of an iterator does not point to any object.

list_data=iter([3,5,7,9,11])
print(next(list_data))
print(next(list_data))
print(next(list_data))
print(next(list_data))
print(next(list_data))
print(next(list_data))
Output
3
5
7
9
11
Traceback (most recent call last): 
File "abc.py", line 7, in <module>              
print(next(list_data))
StopIteration

2.5. KeyboardInterrupt

This error occurs when ctrl+c is pressed which Raised when there is a break in program execution.

name=input('Give me a string') #suppose user entered ctrl+c
Output
Give me a string^CTraceback (most recent call last):
  File "main.py", line 1, in 
    name=input('Give me a string') #suppose user entered ctrl+c
KeyboardInterrupt

3. What is the Difference Between Syntax Error and Exceptions in Python?

In python, the syntax error is referred to such errors which are identified as the wrong statement by the parser. For example, if we miss the colon(:) at the end of if statement.

>>> if x > 1
  File "<stdin>", line 1
    if x > 1
            ^
SyntaxError: invalid syntax

Whereas the exception means syntax in the code was correct but there is some other error which is indicated by the last line at run time.

For example in the code below we are dividing a number by Zero which is correct syntactically but will throw ZeroDivisionError as soon as the statement is executed.

>>> def test(x):
...   if x / 0 == 1:
...     print("Success")
...
>>> test(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
ZeroDivisionError: division by zero

4. AssertionError Exception

With the help of assert keyword we can make sure that the code that we are gonna execute has the correct setup/environment/operating system etc.

In some cases where we have a specific requirement like an Operating System, we can write the assert statement at the beginning of the program to fail fast in case the requirements are not fulfilled. It also prevents the system to go into an undesired state because of unfulfilled dependencies.

In assert keyword, we mention if a particular condition is met then the program will throw an AssertionError exception.

If the condition is found true, then the code will continue. If the condition turns out to be false, the program throws an AssertionError exception.

import sys
assert ('linux' in sys.platform), "This program needs a Linux system."
Output
Traceback (most recent call last):   
File "<input>", line 2, in <module> 
AssertionError: This program needs a Linux system.

Now, the question may arise that how can we handle exceptions in different possible ways. Well, that’s the topic for the next article.


5. Conclusion

In this article we learned about the exception in python along with certain examples for some errors.

  • What is an Exception in Python?
  • Some Common Exceptions in Python
  • Difference between exception error and syntax error
  • AssertionError and asset keyword

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index