Concrete Exceptions
The following are some of the commonly raised exceptions that programmers encounter often.
AssertionError
The AssertionError is raised when an assert statement is false.
Example:
# function to determine the length of the list given
# It also asserts if the length is zero or not
# In case of an empty list it throw a AssertionError with the message provided.
def length(List):
assert len(List)!=0, "No courses available!"
return len(List)
CN_courses=[]
list_length= length(CN_courses)
print(list_length)
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 9, in <module>
list_length= length(CN_courses)
File "main.py", line 5, in length
assert len(List)!=0, "No courses available!"
AssertionError: No courses available!
You can also try this code with Online Python Compiler
Run Code
AttributeError
The AttributeError is raised when an attribute reference or assignment fails.
Example:
# program to illustrate AttributeError
# Strings do not have append() attribute
str1="Coding"
str2="Ninjas"
# This results in AttributeError
str3= str1.append(str2)
print(str3)
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
str3= str1.append(str2)
AttributeError: 'str' object has no attribute 'append'
You can also try this code with Online Python Compiler
Run Code
EOFError
The EOFError is raised when the input() function reaches an end-of-file condition (EOF) without reading any data.
Example:
# program to demonstrate EOFError
# Take first string as the input
str1= input()
# Print the string
print(str1)
# before taking the second string as input
# press ctrl+D to interrupt the program and quit the process
# this will raise an EOFError as the second input was not taken
str2= input()
print(str2)
You can also try this code with Online Python Compiler
Run Code
Output:
Coding
Coding
Traceback (most recent call last):
File "main.py", line 3, in <module>
str2= input()
EOFError
You can also try this code with Online Python Compiler
Run Code
GeneratorExit
The GeneratorExit is not considered to be an error directly. It inherits from the BaseException class rather than the Exception class. This exception is raised when a generator or a coroutine is closed.
ImportError
As the name says, this exception is raised when the program is unable to load the module which the user imports. In most cases either the module is not present at all or the name specified is wrong.
Example:
import CodingNinjas
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import CodingNinjas
ModuleNotFoundError: No module named 'CodingNinjas'
You can also try this code with Online Python Compiler
Run Code
The ModuleNotFoundError is a subclass of ImportError.
IndexError
This type of error is mostly raised when we try to access an illegal index. By illegal index, we mean the index which is out of range of the array or list.
Example:
a=["Coding", "Ninjas"]
# prints Ninjas
#print(a[1])
#IndexError
print(a[4])
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 7, in <module>
print(a[4])
IndexError: list index out of range
You can also try this code with Online Python Compiler
Run Code
KeyError
This error is raised in case a key is tried to be accessed in the mapping, which is not available.
Example:
batsman = { 'Virat':1, 'Dhawan':2, 'Rohit':3 }
# key Dhoni is not present, hence it will raise KeyError
print (batsman['Dhoni'])
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
print (batsman['Dhoni'])
KeyError: 'Dhoni'
You can also try this code with Online Python Compiler
Run Code
KeyboardInterrupt
This exception inherits from the BaseException so that it is not caught by the code that catches Exception. This exception generally arises when the user hits the interrupt key (normally Control-C or Delete).
Example:
#instead of providing any input press ctrl+c
inp= input()
print(inp)
You can also try this code with Online Python Compiler
Run Code
Output:
^CTraceback (most recent call last):
File "main.py", line 1, in <module>
inp= input()
KeyboardInterrupt
You can also try this code with Online Python Compiler
Run Code
MemoryError
This exception is raised when the program runs out of memory.
Example:
my_list=[]
num= 99999999999
for i in range(num):
my_list.append(i)
print(my_list)
You can also try this code with Online Python Compiler
Run Code
Output:
MemoryError
You can also try this code with Online Python Compiler
Run Code
NameError
The NameError exception is raised when a local or global name is not found—for example, an unqualified variable name.
Example:
first="Coding"
second= "Ninjas"
# prints Coding
print(first)
# prints Ninjas
print(second)
# it will raise NameError before third is not defined
print(third)
You can also try this code with Online Python Compiler
Run Code
Output:
Coding
Ninjas
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(third)
NameError: name 'third' is not defined
You can also try this code with Online Python Compiler
Run Code
NotImplementedError
The NotImplementedError occurs in Python when an abstract method lacks the required derived class to override this method, resulting in this exception.
OSError([arg])
This type of exception is raised in case of I/O failures like file not found or in case of system-related errors.
OverflowError
When the result of an arithmetic operation is out of range, the OverflowError is raised. Integers throw MemoryError rather than OverflowError. OverflowError is occasionally thrown for integers that are outside of a specified range. Floating-point values do not throw OverflowError.
Example:
import math
# results in Overflow
x= math.exp(1000)
print(x)
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 2, in <module>
x= math.exp(1000)
OverflowError: math range error
You can also try this code with Online Python Compiler
Run Code
RecursionError
This error is generated when there is infinite recursion. When there is no terminating condition in the recursive function after some time, maximum recursion depth is exceeded, and an exception is raised.
Example:
# recursive function without terminating condition
def recur():
print("Infinite recursion")
recur()
# calling recur()
recur()
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 6, in <module>
recur()
File "main.py", line 4, in recur
recur()
File "main.py", line 4, in recur
recur()
File "main.py", line 4, in recur
recur()
[Previous line repeated 992 more times]
File "main.py", line 3, in recur
print("Infinite recursion")
RecursionError: maximum recursion depth exceeded while calling a Python object.
You can also try this code with Online Python Compiler
Run Code
RuntimeError
A program that has a runtime error has passed the interpreter's syntax checks and begun to execute. However, an error occurred during the execution of one of the program's statements, causing the interpreter to stop executing the program and display an error message. Runtime errors are also known as exceptions because they typically indicate that something unusual has occurred.
StopIteration
The StopIteration error is raised by the built-in function __next__() method. This exception is reached when the iterator tries to access an element that is not available. In such a case, the __next__() method tries to access a value, but no value is available.
Example:
arr = ["Coding", "Ninjas", "Blogs"]
itr=iter(arr)
print (itr)
print (itr.__next__())
print (itr.__next__())
print (itr.__next__())
print (itr.__next__())
You can also try this code with Online Python Compiler
Run Code
Output:
<list_iterator object at 0x7f36e84dd5e0>
Coding
Ninjas
Blogs
Traceback (most recent call last):
File "main.py", line 8, in <module>
print (itr.__next__())
StopIteration
You can also try this code with Online Python Compiler
Run Code
SyntaxError
The SyntaxError is raised when the parser encounters a syntax error.
Example:
name="Coding Ninjas"
# we dont provide : after the if statement
# this will raise a SyntaxError
if name=="Coding Ninjas"
print("Correct!")
else:
print("Incorrect!")
You can also try this code with Online Python Compiler
Run Code
Output:
File "main.py", line 5
if name=="Coding Ninjas"
^
SyntaxError: invalid syntax
You can also try this code with Online Python Compiler
Run Code
SystemError
This error is raised when the interpreter detects an internal error. The user may not be responsible for this error.
TypeError
When an operation or function is applied to an object of the wrong type, a TypeError is thrown. This exception throws a string containing information about the type mismatch.
Example:
name="Coding Ninjas"
arr=[]
# concatenating string with list
# This will raise TypeError
temp=name+arr
print(temp)
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
temp=name+arr
TypeError: can only concatenate str (not "list") to str
You can also try this code with Online Python Compiler
Run Code
ValueError
The ValueError is raised when an invalid value is provided to a particular data type.
Example:
name="Coding Ninjas"
# converting string to int will raise ValueError
print(int(name))
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(int(name))
ValueError: invalid literal for int() with base 10: 'Coding Ninjas'
You can also try this code with Online Python Compiler
Run Code
ZeroDivisionError
This error is generated when a division operation is performed such that the denominator is zero.
Example:
print(5/0)
You can also try this code with Online Python Compiler
Run Code
Output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(5/0)
ZeroDivisionError: division by zero
You can also try this code with Online Python Compiler
Run Code
Also see, Convert String to List Python
FAQs
1.What are exceptions?
Exceptions are errors that occur during execution. In Python, all the exception classes are derived from the BaseException class.
2. What is the difference between BaseException and Exception class in Python?
BaseException class is not directly inherited by user-defined classes, whereas user-defined classes are derived from the Exception class.
3. Name a few errors that can raise ArithmeticError exceptions.
ArithmeticError exceptions are raised by arithmetic errors like OverflowError, ZeroDivisionError, FloatingPointError.
4. Name some commonly encountered errors.
Some commonly encountered errors are SyntaxError, TypeError, IndexError, ZeroDivisionError, KeyError and ImportError.
Conclusion
In this article, we have extensively discussed built-in exceptions in Python, along with a code demonstration of various exceptions.
- Exceptions are errors that occur during execution. In Python, all the exception classes are derived from the BaseException class.
-
Some commonly encountered errors are SyntaxError, TypeError, IndexError, ZeroDivisionError, KeyError and ImportError.
Recommended Readings:
We hope that this blog has helped you enhance your knowledge regarding built-in exceptions in Python and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!