9/2/24, 2:22 PM (02-09-2024)
Exception
These are the errors that occur during the execution of a program.
When an error occurs, python stops the normal flow of the program and raises an
Exception.
When the Exception is not handled, the program will terminate and display a
traceback error message.
Types of errors
Name error
Valu error
Type error
Syntax error
Index error
Arithmetic error
Import module error
File not found error
In [4]: # Nameerror - When the variable is not defined
print(a)
print(2*2)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 1
----> 1 print(a) # Nameerror
2 print(2*2)
NameError: name 'a' is not defined
Whenever an exception occurs in our program and it is not handled by the program
, it generates a detailed report about what went wrong.
In [6]: ## Valuerror - whenever incorrect datatype is given to a correct function.
a=int(input())
print(a)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[6], line 2
1 ## Valuerror
----> 2 a=int(input())
3 print(a)
ValueError: invalid literal for int() with base 10: 'a'
In [16]: ## Type error - When a function is applied for unsupported datatype
print(len('sravya'))
print(len(10))
localhost:8888/lab? 1/6
9/2/24, 2:22 PM (02-09-2024)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[16], line 3
1 ## Typeerror - When a function is applied for unsupported datatype
2 print(len('sravya'))
----> 3 print(len(10))
TypeError: object of type 'int' has no len()
In [32]: ## Syntax error - When there is an invalid syntax
a=10
print(a
Cell In[32], line 3
print(a
^
SyntaxError: incomplete input
In [34]: ## Arithmetic Error - Raised when error occurs in arithmetic operations
## Zerodivisionerror
print(5/0)
print(5%0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[34], line 3
1 ## Arithmetic Error - Raised when error occurs in arithmetic operations
2 ## Zerodivisionerror
----> 3 print(5/0)
4 print(5%0)
ZeroDivisionError: division by zero
In [36]: ## Index error
a=[1,2,5,6,4]
print(a[5])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[36], line 3
1 ## Index error
2 a=[1,2,5,6,4]
----> 3 print(a[5])
IndexError: list index out of range
In [42]: ## Import error
import maths
print(maths.sqrt(16))
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[42], line 2
1 ## Import error
----> 2 import maths
3 print(maths.sqrt(16))
ModuleNotFoundError: No module named 'maths'
localhost:8888/lab? 2/6
9/2/24, 2:22 PM (02-09-2024)
In [64]: ## Filenotfounderror
file=open("sample2.txt",'r')
content=file.read()
print(content)
file.close()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[64], line 2
1 ## Filenotfounderror
----> 2 file=open("sample2.txt",'r')
3 content=file.read()
4 print(content)
File ~\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py:324, in _modi
fied_open(file, *args, **kwargs)
317 if file in {0, 1, 2}:
318 raise ValueError(
319 f"IPython won't let you open fd={file} by default "
320 "as it is likely to crash IPython. If you know what you are doin
g, "
321 "you can use builtins' open."
322 )
--> 324 return io_open(file, *args, **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: 'sample2.txt'
To handle all these type of errors, we use try and except blocks.
Try and except blocks are used to handle the exceptions(errors) that may occur
during the execution of a program.
This allows your program to continue running even when an error occurs, rather
than crashing.
Syntax : try: #code except ExceptionType: #Code that runs if the specified exception
occurs
In [76]: ## Nameerror
try:
print(m)
except Exception as e:
print(e)
name 'm' is not defined
In [80]: ## Value error
try:
a=int(input())
print(a)
except Exception as b:
print(b)
invalid literal for int() with base 10: 'a'
In [104… ## Arithmetic error
try:
b=int(input())
print(b)
a=55/0
localhost:8888/lab? 3/6
9/2/24, 2:22 PM (02-09-2024)
print(a)
except ValueError:
print('invalid input')
except ZeroDivisionError:
print('cant divide a number by zero')
5
cant divide a number by zero
In [110… ## Index error
a=[5,4,2,4]
try:
print(a[4])
except Exception as e:
print(e)
list index out of range
In [112… ## Type error
try:
print(len(5))
except Exception as e:
print(e)
object of type 'int' has no len()
In [116… ## Import Module
try:
import maths
print(maths.sqrt(9))
except Exception as e:
print(e)
No module named 'maths'
In [118… ## File not found error
try:
file=open('file3.txt','r')
content=file.open()
print(content)
file.close()
except Exception as e:
print(e)
[Errno 2] No such file or directory: 'file3.txt'
In [148… ## Key error
# If the key doesnot exist in the dictionary then it will give keyerror
dict={1:2,3:4,5:6}
print(dict[13])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[148], line 3
1 ## Key error
2 dict={1:2,3:4,5:6}
----> 3 print(dict[13])
KeyError: 13
In [140… ## Raising Exceptions manually (use RAISE keyword)
try:
localhost:8888/lab? 4/6
9/2/24, 2:22 PM (02-09-2024)
age=int(input())
if age<0:
raise Exception('Age cannot be negative')
print(age)
except Exception as e:
print(e)
In [144… try:
age=int(input())
print(age)
except NameError as e:
print(e)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[144], line 2
1 try:
----> 2 age=int(input())
3 print(age)
4 except NameError as e:
ValueError: invalid literal for int() with base 10: 'sd'
In [9]: ## Attribute error
# Whenever we try to call a method which doesn't exist in that class
class Sravya:
def char(self):
print('Genuine')
s=Sravya()
s.char1()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[9], line 7
5 print('Genuine')
6 s=Sravya()
----> 7 s.char1()
AttributeError: 'Sravya' object has no attribute 'char1'
In [25]: ## Asking age of the user
try:
age=int(input())
print(age)
except Exception as e:
print(e)
finally:
print('Task completed')
print('hii to all')
print(2*5)
invalid literal for int() with base 10: 'ds'
Task completed
hii to all
10
Usage of Exceptions
localhost:8888/lab? 5/6
9/2/24, 2:22 PM (02-09-2024)
Error handling
Input validation
Raising custom exceptions
Disadvantages :
Performance Overhead = Instead of catching the frequent exceptions for
multiple times, its better to stop at the first occurence.
Complexity
localhost:8888/lab? 6/6