0% found this document useful (0 votes)
20 views21 pages

Exception-Handling VHA

The document discusses different types of exceptions in Python including built-in exceptions like AttributeError and ImportError as well as syntax errors. It provides examples of various exceptions being raised in code snippets.

Uploaded by

advait
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views21 pages

Exception-Handling VHA

The document discusses different types of exceptions in Python including built-in exceptions like AttributeError and ImportError as well as syntax errors. It provides examples of various exceptions being raised in code snippets.

Uploaded by

advait
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

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.

All exceptions are represented as classes in


Python.
There are 2 stages where error may happen in a program

During compilation -> Syntax Error

Something in the program is not written according to the program grammar.


Error is raised by the interpreter/compiler
You can solve it by rectifying the program

Other examples of syntax error


Leaving symbols like colon,brackets
Misspelling a keyword
Incorrect indentation
empty if/else/loops/class/functions

During execution -> 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)

ImportError: Raised when an imported module does not exist

IndentationError: Raised when indentation is not correct

IndexError: Raised when an index of a sequence does not exist

KeyError: Raised when a key does not exist in a dictionary

NameError: Raised when a variable does not exist

SyntaxError: Raised when a syntax error occurs

TypeError: Raised when two different types are combined

ValueError: Raised when there is a wrong value in a specified data type

ZeroDivisionError Raised when the second operator in a division is zero

In [29]: 1 h = input("this is"

File "<ipython-input-29-e00974fe9829>", line 1


h = input("this is"
^
SyntaxError: unexpected EOF while parsing

In [28]: 1 student = {
2 "name": "John",
3 "level": "400",
4 "faculty": "Engineering and Technology"
5 ​

File "<ipython-input-28-dc74c25d4bb5>", line 4


"faculty": "Engineering and Technology"
^
SyntaxError: unexpected EOF while parsing

In [30]: 1 for i in sample.txt:

File "<ipython-input-30-60a88ca51960>", line 1


for i in sample.txt:
^
SyntaxError: unexpected EOF while parsing

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:

File "<ipython-input-31-de9ce877e47c>", line 1


class P:
^
SyntaxError: unexpected EOF while parsing

In [1]: 1 # Examples of syntax error


2 print 'hello world'

File "<ipython-input-1-4655b84ba7b7>", line 2


print 'hello world'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('h
ello world')?

In [2]: 1 a = 5
2 if a==3
3 print('hello')

File "<ipython-input-2-efc58c10458d>", line 2


if a==3
^
SyntaxError: invalid syntax

In [3]: 1 a = 5
2 iff a==3:
3 print('hello')

File "<ipython-input-3-d1e6fae154d5>", line 2


iff a==3:
^
SyntaxError: invalid syntax

In [4]: 1 var = 5
2 if var==3:
3 print('hello')

File "<ipython-input-4-e9da9a582f84>", line 3


print('hello')
^
IndentationError: expected an indented block

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]

IndexError: list index out of range

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)

ModuleNotFoundError: No module named 'mathi'

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'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

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')

ValueError: invalid literal for int() with base 10: '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)

NameError: name 'k' is not defined

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()

AttributeError: 'list' object has no attribute 'upper'

ArithmeticError is simply an error that occurs


during numeric calculations.
ArithmeticError types in Python include:

OverFlowError

ZeroDivisionError

FloatingPointError

In [13]: 1 print("Simple program for showing overflow error")


2 print("\n")
3 import math
4 print("The exponential value is")
5 print(math.exp(1000))

Simple program for showing overflow error

The exponential value is

--------------------------------------------------------------------------
-
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))

OverflowError: math range error

localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 6/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

In [12]: 1 arithmetic = 5/0


2 print(arithmetic)

--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
<ipython-input-12-888908747809> in <module>
----> 1 arithmetic = 5/0
2 print(arithmetic)

ZeroDivisionError: division by zero

Why is it important to handle exceptions


When an exception occurs, the program terminates suddenly.

Suddenly termination of program may corrupt the program.

Exception may cause data loss from the database or a file.

how to handle exceptions

Try – The try block contains code which may


cause exceptions.
Syntax-

try:

statements

Except – The except block is used to catch an


exception that is raised in the try block. There
can be multiple except block for try block.
Syntax-

except ExceptionName:

statements

Else – This block will get executed when no


exception is raised. Else block is executed
after try block.
localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 7/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

Syntax-

else:

statements

Finally – This block will get executed


irrespective of whether there is an exception
or not.
Syntax-

finally:

statements

We can write several except blocks for a


single try block.
We can write multiple except blocks to handle multiple exceptions.

We can write try block without any except blocks.

We can not write except block without a try block.

Finally block is always executed irrespective of whether there is an exception or not.

Else block is optional.

Finally block is optional.

#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

how to write except block


1.With the Exception Class Name

except ExceptionClassName:

Statement

2.Exception as an object

except ExceptionClassName as obj:

Statement

3.Multiple Exception within tuple

except (ExceptionClassName1, ExceptionClassName2, Exceptio


nClassName3, …… ):

Statement

4.Catch any Type of Exception

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 [17]: 1 # let's create a file


2 with open('sample.txt','w') as f:
3 f.write('hello world')

In [18]: 1 # try catch demo


2 try:
3 with open('sample1.txt','r') as f:
4 print(f.read())
5 except:
6 print('sorry file not found')

sorry file not found

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

In [19]: 1 # catching specific exception


2 try:
3 m=5
4 f = open('sample1.txt','r')
5 print(f.read())
6 print(m)
7 print(5/2)
8 L = [1,2,3]
9 L[100]
10 except FileNotFoundError:
11 print('file not found')
12 except NameError:
13 print('variable not defined')
14 except ZeroDivisionError:
15 print("can't divide by 0")
16 except Exception as e:
17 print(e)

file not found

localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 10/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

In [1]: 1 # catching specific exception


2 try:
3 #m=5
4 f = open('sample.txt','r')
5 print(f.read())
6 print(m)
7 print(5/2)
8 L = [1,2,3]
9 L[100]
10 except FileNotFoundError:
11 print('file not found')
12 except NameError:
13 print('variable not defined')
14 except ZeroDivisionError:
15 print("can't divide by 0")
16 except Exception as e:
17 print(e)

hello world
variable not defined

In [2]: 1 # catching specific exception


2 try:
3 m=5
4 f = open('sample.txt','r')
5 print(f.read())
6 print(m)
7 print(5/0)
8 L = [1,2,3]
9 L[100]
10 except FileNotFoundError:
11 print('file not found')
12 except NameError:
13 print('variable not defined')
14 except ZeroDivisionError:
15 print("can't divide by 0")
16 except Exception as e:
17 print(e)

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

In [3]: 1 # catching specific exception


2 try:
3 m=5
4 f = open('sample.txt','r')
5 print(f.read())
6 print(m)
7 print(5/2)
8 L = [1,2,3]
9 L[100]
10 except FileNotFoundError:
11 print('file not found')
12 except NameError:
13 print('variable not defined')
14 except ZeroDivisionError:
15 print("can't divide by 0")
16 except Exception as e:
17 print(e)

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())

file nai mili

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')

file nai mili


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')

Division by Zero Not allowed


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')

Division by Zero Not allowed


Inside Finally
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')

name 'g' is not defined


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')

name 'g' is not defined


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.

Syntax:- assert condition, error_message

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

In [10]: 1 n=int(input("enter int"))


2 assert n>5,"enter valid number"

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"

AssertionError: enter valid number

User Defined Exception


A programmer can create his own exceptions, called user-defined exceptions or Custom
Exception.

1.Creating Exception Class using Exception Class as a Base Class

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):

def __init__(self, arg):

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

In [11]: 1 class BalanceException (Exception):


2 #pass
3 def __init__(self, arg):
4 self.msg = arg
5
6 def checkbalance():
7 money = 10000
8 withdraw = 9000
9 try:
10 balance = money - withdraw
11 if(balance<=2000):
12 raise BalanceException('Insufficient Balance')
13 print(balance)
14 except BalanceException as be:
15 print(be)
16
17 checkbalance()

Insufficient Balance

Raising Exception
raise statement is used to raise the user defined exception.

raise MyException(‘message’)

In [16]: 1 # raise Exception


2 # In Python programming, exceptions are raised when errors occur at run
3 # We can also manually raise exceptions using the raise keyword.
4 ​
5 # We can optionally pass values to the exception to clarify why that ex
6 ​
7 raise ZeroDivisionError('aise hi ')
8 # Java
9 # try -> try
10 # except -> catch
11 # raise -> throw
12 ​

--------------------------------------------------------------------------
-
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

In [18]: 1 money = 10000


2 withdraw = 9000
3 try:
4 balance = money - withdraw
5 if(balance<=2000):
6 raise BalanceException('Insufficient Balance')
7 print(balance)
8 except BalanceException as be:
9 print(be)

Insufficient Balance

In [12]: 1 class Bank:


2 ​
3 def __init__(self,balance):
4 self.balance = balance
5 ​
6 def withdraw(self,amount):
7 if amount < 0:
8 raise Exception('amount cannot be -ve')
9 if self.balance < amount:
10 raise Exception('paise nai hai tere paas')
11 self.balance = self.balance - amount
12 ​
13 obj = Bank(10000)
14 try:
15 obj.withdraw(15000)
16 except Exception as e:
17 print(e)
18 else:
19 print(obj.balance)

paise nai hai tere paas

localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 18/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

In [13]: 1 class MyException(Exception):


2 def __init__(self,message):
3 print(message)
4 ​
5 class Bank:
6 ​
7 def __init__(self,balance):
8 self.balance = balance
9 ​
10 def withdraw(self,amount):
11 if amount < 0:
12 raise MyException('amount cannot be -ve')
13 if self.balance < amount:
14 raise MyException('paise nai hai tere paas')
15 self.balance = self.balance - amount
16 ​
17 obj = Bank(10000)
18 try:
19 obj.withdraw(5000)
20 except MyException as e:
21 pass
22 else:
23 print(obj.balance)

5000

localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 19/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

In [14]: 1 class SecurityError(Exception):


2 ​
3 def __init__(self,message):
4 print(message)
5 ​
6 def logout(self):
7 print('logout')
8 ​
9 class Google:
10 ​
11 def __init__(self,name,email,password,device):
12 self.name = name
13 self.email = email
14 self.password = password
15 self.device = device
16 ​
17 def login(self,email,password,device):
18 if device != self.device:
19 raise SecurityError('bhai teri to lag gayi')
20 if email == self.email and password == self.password:
21 print('welcome')
22 else:
23 print('login error')
24 ​
25 ​
26 ​
27 obj = Google('nitish','[email protected]','1234','android')
28 ​
29 try:
30 obj.login('[email protected]','1234','windows')
31 except SecurityError as e:
32 e.logout()
33 else:
34 print(obj.name)
35 finally:
36 print('database connection closed')

bhai teri to lag gayi


logout
database connection closed

Handling Exception
Using try and except block Programmer can handle exceptions.

try:

statement

except MyException as mye:

statement

localhost:8888/notebooks/T3-PYTHON1/Exception-handling_VHA.ipynb 20/21
1/6/24, 6:54 AM Exception-handling_VHA - Jupyter Notebook

In [19]: 1 # catching specific exception


2 try:
3 m=5
4 f = open('sample.txt','r')
5 print(f.read())
6 print(m)
7 print(5/2)
8 L = [1,2,3]
9 L[100]
10 ​
11 except Exception as e:
12 print(e)

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.

An exception which are not handled by programmer, becomes an error.

All exceptions occur only at runtime.

Error may occur at compile time or runtime.

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

You might also like