29 exception in python

 

1. An exception is an event, which occurs during the execution of a program.

2. Using try,except,else and finally block we can handle exception.

3. Using exceptions we can handle run time errors.


# else

1. else block will execute when the try block executed successfully with out any errors.


# Finally ***

1. finally block will execute both times when try block executed successfully or fail.

2. It is used to do the cleanup process.


1) try and except 


import sys


d = {'A':1,'B':2}

try:

    d['C']

    'we' + '123'

    sys.ok()

    import re

    open('2_else.py')

except ModuleNotFoundError:

    print(' Module is not defined ')

except NameError:

    print(' name is not defined please define ')

except KeyError:

    print(' KeyError ')

except FileNotFoundError as e:

    print(' Please define file ', e)

except:

    print(' Try block got failed ')


2)else block

#'''

#1. else block will execute when the try block executed successfully with out any errors.

#'''

try:

    a = '10'

    b = '20'

    c = a + b

except:

    print(' Try block got failed ')

else:

    print('Else block is')

3) finally
#'''
#1. finally block will execute both times when try block executed successfully or fail.
#2. It is used to do cleanup process
(Closing File, Killing process, close remote connections like that).
#'''
try:
    fh = open('3_finally.py')
    print(fh.readline())
    print('12' + '13')
except:
    print(' Try block got failed')
else:
    print(' Else block ')
finally:
    fh.close()
    print(' Finally block ')

4) raise exception

# Using raise keyword we can raise exception manually.

num = 13


if num <= 15 :
    raise AssertionError(' Number should be more than 15')


print(' END ')

Comments

Popular posts from this blog

1 PYTHON PROGRAMMING

4 Tuple data types

2 String data types