Exception-Handling VHA
Exception-Handling VHA
Exception-handling
An exception is a runtime error which can be handled by the programmer. All exceptions are
represented as classes in Python.
Type of Exception:-
Built-in Exception – Exceptions which are already available in Python Language. The base
class for all built-in exceptions is BaseException class.
User Defined Exception – A programmer can create his own exceptions, called user-defined
exceptions.
Exception Description
ArithmeticError: Raised when an error occurs in numeric calculations
AttributeError: Raised when attribute reference or assignment fails Exception Base class for
all exceptions
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 1/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
EOFError: Raised when the input() method hits an "end of file" condition (EOF)
In [28]: 1 student = {
2 "name": "John",
3 "level": "400",
4 "faculty": "Engineering and Technology"
5
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 2/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [31]: 1 class P:
In [2]: 1 a = 5
2 if a==3
3 print('hello')
In [3]: 1 a = 5
2 iff a==3:
3 print('hello')
In [4]: 1 var = 5
2 if var==3:
3 print('hello')
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 3/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [5]: 1 # IndexError
2 # The IndexError is thrown when trying to access an item at an invalid
3 L = [1,2,3]
4 L[100]
--------------------------------------------------------------------------
-
IndexError Traceback (most recent call las
t)
<ipython-input-5-c90668d2b194> in <module>
2 # The IndexError is thrown when trying to access an item at an inv
alid index.
3 L = [1,2,3]
----> 4 L[100]
In [6]: 1 # ModuleNotFoundError
2 # The ModuleNotFoundError is thrown when a module could not be found.
3 import mathi
4 math.floor(5.3)
--------------------------------------------------------------------------
-
ModuleNotFoundError Traceback (most recent call las
t)
<ipython-input-6-cbdaf00191df> in <module>
1 # ModuleNotFoundError
2 # The ModuleNotFoundError is thrown when a module could not be fou
nd.
----> 3 import mathi
4 math.floor(5.3)
In [7]: 1 # KeyError
2 # The KeyError is thrown when a key is not found
3
4 d = {'name':'nitish'}
5 d['age']
--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
<ipython-input-7-453afa1c9765> in <module>
3
4 d = {'name':'nitish'}
----> 5 d['age']
KeyError: 'age'
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 4/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [8]: 1 # TypeError
2 # The TypeError is thrown when an operation or function is applied to a
3 1 + 'a'
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-8-2a3eb3f5bb0a> in <module>
1 # TypeError
2 # The TypeError is thrown when an operation or function is applied
to an object of an inappropriate type.
----> 3 1 + 'a'
In [9]: 1 # ValueError
2 # The ValueError is thrown when a function's argument is of an inapprop
3 int('a')
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
<ipython-input-9-e419d2a084b4> in <module>
1 # ValueError
2 # The ValueError is thrown when a function's argument is of an ina
ppropriate type.
----> 3 int('a')
In [10]: 1 # NameError
2 # The NameError is thrown when an object could not be found.
3 print(k)
--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
<ipython-input-10-e3e8aaa4ec45> in <module>
1 # NameError
2 # The NameError is thrown when an object could not be found.
----> 3 print(k)
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 5/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [11]: 1 # AttributeError
2 L = [1,2,3]
3 L.upper()
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
<ipython-input-11-dd5a29625ddc> in <module>
1 # AttributeError
2 L = [1,2,3]
----> 3 L.upper()
OverFlowError
ZeroDivisionError
FloatingPointError
--------------------------------------------------------------------------
-
OverflowError Traceback (most recent call las
t)
<ipython-input-13-a3e7e3f1c25a> in <module>
3 import math
4 print("The exponential value is")
----> 5 print(math.exp(1000))
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 6/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
<ipython-input-12-888908747809> in <module>
----> 1 arithmetic = 5/0
2 print(arithmetic)
try:
statements
except ExceptionName:
statements
Syntax-
else:
statements
finally:
statements
#example 1
try:
Statement
except ExceptionClassName:
Statement
#example2
try:
Statement
except ExceptionClassName:
Statement
else:
Statement
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 8/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
finally:
Statement
#example 3
try:
Statement
except ExceptionClassName1:
Statement
except ExceptionClassName2:
Statement
finally:
Statement
#example4
try:
Statement
except ExceptionClassName:
Statement
2.Exception as an object
Statement
Statement
except:
Statement
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 9/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [20]: 1 a = 10
2 b = 0
3 try:
4 d = a/b
5 print(d)
6
7 except:
8 print('Exception Handler')
9
10 print('Rest of the Code')
Exception Handler
Rest of the Code
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 10/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
hello world
variable not defined
hello world
5
can't divide by 0
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 11/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
hello world
5
2.5
list index out of range
In [4]: 1 # else
2 try:
3 f = open('sample1.txt','r')
4 except FileNotFoundError:
5 print('file nai mili')
6 except Exception:
7 print('kuch to lafda hai')
8 else:
9 print(f.read())
In [5]: 1 # else
2 try:
3 f = open('sample.txt','r')
4 except FileNotFoundError:
5 print('file nai mili')
6 except Exception:
7 print('kuch to lafda hai')
8 else:
9 print(f.read())
hello world
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 12/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [6]: 1 # finally
2 # else
3 try:
4 f = open('sample1.txt','r')
5 except FileNotFoundError:
6 print('file nai mili')
7 except Exception:
8 print('kuch to lafda hai')
9 else:
10 print(f.read())
11 finally:
12 print('ye to print hoga hi')
In [7]: 1 # finally
2 # else
3 try:
4 f = open('sample.txt','r')
5 except FileNotFoundError:
6 print('file nai mili')
7 except Exception:
8 print('kuch to lafda hai')
9 else:
10 print(f.read())
11 finally:
12 print('ye to print hoga hi')
hello world
ye to print hoga hi
In [21]: 1 a = 10
2 b = 0
3 try:
4 d = a/b
5 print(d)
6 print('Inside Try')
7
8 except ZeroDivisionError:
9 print('Division by Zero Not allowed')
10
11 print('Rest of the Code')
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 13/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [22]: 1 a = 10
2 b = 5
3 try:
4 d = a/b
5 print(d)
6 print('Inside Try')
7
8 except ZeroDivisionError:
9 print('Division by Zero Not allowed')
10
11 else:
12 print('Inside Else')
13
14 print('Rest of the Code')
2.0
Inside Try
Inside Else
Rest of the Code
In [23]: 1 a = 10
2 b = 0
3 try:
4 d = a/b
5 print(d)
6 print('Inside Try')
7
8 except ZeroDivisionError:
9 print('Division by Zero Not allowed')
10
11 else:
12 print('Inside Else')
13
14 finally:
15 print('Inside Finally')
16
17 print('Rest of the Code')
In [24]: 1 a = 10
2 b = 0
3 try:
4 d = a/b
5 print(d)
6 print('Inside Try')
7
8 except ZeroDivisionError as obj:
9 print(obj)
10
11 print('Rest of the Code')
division by zero
Rest of the Code
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 14/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
In [25]: 1 a = 10
2 b = 0
3 try:
4 d = a/g
5 print(d)
6
7 except ZeroDivisionError as obj:
8 print(obj)
9
10 except NameError as ob:
11 print(ob)
12
13 print('Rest of the Code')
In [26]: 1 a = 10
2 b = 0
3 try:
4 d = a/g
5 print(d)
6
7 except (NameError, ZeroDivisionError) as obj:
8 print(obj)
9
10 print('Rest of the Code')
Assert Statement
The assert Statement is useful to ensure that a given condition is True. If it is not true, it
raises AssertionError.
If the condition is False then the exception by the name AssertionError is raised along with
the message.
If message is not given and the condition is False then also AssertionError is raised without
message.
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 15/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
enter int4
--------------------------------------------------------------------------
-
AssertionError Traceback (most recent call las
t)
<ipython-input-10-fa83f5a7736c> in <module>
1 n=int(input("enter int"))
----> 2 assert n>5,"enter valid number"
2.Raising Exception
3.Handling Exception
Creating Exception
#We can create our own exception by creating a sub class to built-in Exception class.
class MyException(Exception):
pass
class MyException(Exception):
self.msg = arg
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 16/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
Insufficient Balance
Raising Exception
raise statement is used to raise the user defined exception.
raise MyException(‘message’)
--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
<ipython-input-16-97b461be5f2b> in <module>
5 # We can optionally pass values to the exception to clarify why th
at exception was raised
6
----> 7 raise ZeroDivisionError('aise hi ')
8 # Java
9 # try -> try
ZeroDivisionError: aise hi
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 17/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
Insufficient Balance
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 18/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
5000
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 19/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
Handling Exception
Using try and except block Programmer can handle exceptions.
try:
statement
statement
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 20/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook
hello world
5
2.5
list index out of range
Error vs Exception
An exception is an error that can be handled by a programmer.
Error vs Warning
It is compulsory to handle all error otherwise program will not execute, while warning
represents a caution and even though it is not handled, the program will execute.
Errors are derived as sub class of StandardError, while warning derived as sub class from
Warning class.
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 21/21