Cyberithub

Error and Built-In Exceptions in Python with Best Examples

Advertisements

In this tutorial we are going to look into Built-In Exceptions in Python with Best Examples. In the previous article we have covered the concept of shallow and deep copy of python. Now we will go ahead and will look into the error and built-in exceptions concepts in Python. If you are writing a Python code then there will always be a chance that you will see some error while compiling and running that code. Those errors could be syntactical errors, logical errors or some other kind of errors. We will try to understand the types of error and built-in exceptions in Python with the help of examples.

Error and Built-In Exceptions in Python with Best Examples

Error and Built-In Exceptions In Python with Best Examples

Also Read: Shallow and Deep: Types of Copy in Python with Best Examples

There are basically two types of Error and Built-In Exceptions in Python: Syntax Error and Logical Error. One more exception called User defined exceptions in python which will be explained on later articles. As of now, let's keep our focus on below errors and exceptions in python.

  • Syntax Error (Parsing error)
  • Logical Error (Exceptions)

Syntax Error

1. Syntax error

This is a very common error in Python which occurs due to incorrect usage of Syntax.

Program Example

def func()
print("Hello There!")
func()

Program Output

File "<string>", line 1
def func()
^
SyntaxError: invalid syntax

2. IndentationError

This error usually occurs when you does not place the tabs and spaces properly in the code as you can see from below demonstration.

Program Example

def func():
print("Hello There!")
func()

Program Output

File "<string>", line 2
print("Hello There!")
^
IndentationError: expected an indented block

Logical Error

1. AssertionError

Assertion is a concept in python which developer uses to validate input before running the code. If the condition defined in assert statement comes out as true, it simply move to the next line and execute. If condition is false, it will raise an AssertError and print the message if provided for the error else will only raise the error.

Program Example

def Assert(age):
assert (age >0), "You are not human"
if age <= 40:
print("You will hit 40")
if age>40:
print("You already  hit 40")
Assert(35)
Assert(102)
Assert(-2)

Program Output

You will hit 40
You already  hit 40
Traceback (most recent call last):
File "<string>", line 13, in <module>
File "<string>", line 2, in Assert
AssertionError: You are not human

2. AttributeError

AttributeError in python occurs when we try to reference undefined(invalid) attribute or if assignment fails. In below example there is no 'ar' attribute defined in the class. Hence it will throw an error while execution.

Program Example

class Attribute():
def __init__(self):
self.leng = 20
self.bred = 10
self.area = self.leng*self.bred
A = Attribute()
print(A.ar)

Program Output

Traceback (most recent call last):
File "<string>", line 9, in <module>
AttributeError: 'Attribute' object has no attribute 'ar'

3. EOFError

EOFError occurs when either of built in functions input()/raw_input() witnesses EOF(end of file) condition without actually reading any Such error can be seen occurred when we use any online python IDEs where there is no user-console interaction.

Program Example

class Citizen:
def Decide(self, n):
if n >60:
print ("You are senior citizen")
else:
print("You are not senior citizen as below 60")
print ("Enter your age")
n = int(input())
A = Citizen()
A.Decide(n)

Program Output

Enter your age
Traceback (most recent call last):
File "main.py", line 11, in <module>
n = int(input())
EOFError: EOF when reading a line

4. FloatingPointError

This errors occurs due to incorrect floating point calculation done in python program. One simple example can be shown below using print statement.

Example

print(1.1*3)

5. ImportError

ImportError occurs in two cases. First, if we try to import a valid sub-module from a wrong module(example is below). Second, if we try to import non existing module.

Program Example

from os import subprocess

Program Output

Traceback (most recent call last):
File "main.py", line 3, in <module>
from os import subprocess
ImportError: cannot import name subprocess

6. IndexError

IndexError occurs whenever we try to access out of range element from the list, set or any other container. We can also call it out of bound error.

Program Example

list1 = [1,2,3,4]
print(list1[3])
print(list1[4])

Program Output

4
Traceback (most recent call last):
File "<string>", line 3, in <module>
IndexError: list index out of range

7. KeyError

KeyError in python occurs whenever we try to retrieve key which is not present or couldn't be found. This is also called as LookupError.

Program Example

Name = {"Adam":30, "Aina":27, "Nancy":32}
print(Name["Adam"])
print(Name["Marry"])

Program Output

30
Traceback (most recent call last):
File "<string>", line 3, in <module>
KeyError: 'Marry'

8. KeyboardInterrupt

KeyboardInterrupt error in python occur whenever user interrupt the normal execution of a program. Normally we press Ctrl+c to interrupt the execution. In below example, when it asks for user input to enter a number, press Ctrl+c . It will throw the error.

Program Example

print("Enter number")
num= int(input())
if num<50:
print("Under half of 100")
else:
print("Above half of 100")

Program Output

Traceback (most recent call last):
File "sweta.py", line 2, in <module>
num = int(input())
KeyboardInterrupt

9. MemoryError 

MemoryError in python is exactly what we are calling it. It is thrown whenever during a program execution no memory is found. Typically this error occurs when we are dealing with large data sets. We prefer using batch processing in such cases. This is another type of exceptions in Python.

10. NameError

NameError in python occurs whenever the variable program try to access is not defined either in local or global scope. In below example, there is no such variable called 'nam'. Hence an error is thrown at run time. This is a very frequent occurred Exceptions in Python.

Program Example

print("Enter your Name")
name = input()
print("Hello", nam)

Program Output

Enter your Name
Anna
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Anna' is not defined

11. UnicodeEncodeError

This error occurs when you try to encode the non-English characters in your Python code to stream of bytes.

12. UnicodeDecodeError 

UnicodeDecodeError occurs when you try to convert non-ASCII strings to unicode string without mentioning the encoding of the original string.

13. UnicodeTranslateError

This kind of error occur when Unicode string fails to translate into sequence of bytes. More about Unicode on Python Official Documentation.

14. ValueError

This error occurs when a variable or function receives a value or argument of correct type but with inappropriate value. This can be easily understand by using below example.

Program Example

import math
def sqroot(a):
c = math.sqrt(a)
print(c)
sqroot(-4)

Program Output

Traceback (most recent call last):
File "<string>", line 6, in <module>
File "<string>", line 4, in sqroot
ValueError: math domain error

15. ZeroDivisionError

This error indicates that value used in the denominator section of a division is 0. This error can be verified by using below example.

Program Example

import math
def power(a,b):
c = pow(a,b)
print(c)
power(0, -1)

Program Output

Traceback (most recent call last):
File "<string>", line 6, in <module>
File "<string>", line 4, in power
ZeroDivisionError: 0.0 cannot be raised to a negative power

16. OverflowError

OverflowError in python indicates that the arithmetic operation in current program execution has exceeded the limit of current python runtime.

Program Example

a = 3216
result = 2.1/(17.2**a) -12.3/(4.4+2.0*a) + 14.4/(9.2*4.0+2.1) + 1.1*(2.1/3.6*a)
print(result)

Program Output

Traceback (most recent call last):
File "<string>", line 2, in <module> OverflowError: (34, 'Numerical result out of range')

17. StopIteration

Whenever iterator prints the last element in the list, it’s next() function raises StopIteration error if further try to access non existence elements.

Program Example

list1= [2,3,5]
a=iter(list1)
print(next(a))
print(next(a))
print(next(a))
print(next(a))

Program Output

2
3
5
Traceback (most recent call last):
File "<string>", line 7, in <module> StopIteration

18. TabError

TabError in python occurs when indentation have irregular spaces and tabs .

19. SystemError

SystemError in python occurs whenever interpreter detects any internal error.

20. TypeError

TypeError in python occurs whenever there is mismatch in the value on which operation is expected to be performed. In below example, function func() is expecting int value to perform addition. Since we have passed a string to perform addition, it throws an error.

Program Example

def func(num):
sum = num+ 2
print(sum)
func("Ally")

Program Output

Traceback (most recent call last):
File "<string>", line 4, in <module>
File "<string>", line 2, in func
TypeError: can only concatenate str (not "int") to str

21. UnboundLocalError

UnboundLocalError in python occurs when we try to reference the local variable before it has been assigned. In below example we are trying to assign to local variable ‘sum’ which is defined as global. Python can’t detect the variable locally. Hence an error is thrown.

Program Example

sum =0
def func(num):
sum= num+ sum
print(sum)
func(2)

Program Output

Traceback (most recent call last):
File "<string>", line 6, in <module>
File "<string>", line 4, in func
UnboundLocalError: local variable 'sum' referenced before assignment

22. UnicodeError 

UnicodeError in python is common and occur whenever we try to misuse ‘\’ in our code. ‘\’ has pre defined meaning in python which is called “escape character”.

Program Example

import pandas
pandas.read_csv("C:\Users\Eric\Desktop\Demo.txt", "r", encoding="utf-8")

Program Output

File "<string>", line 2
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

 

 

Leave a Comment