Thursday, July 1, 2021

Python - Exception handling

There are many built in exceptions which are raised in python when something goes wrong. Exceptions in python can be handled using a try statement. The code that handles the exception is written in the except clause.

try:

    #code

except Exception as e:

    print(e)

when the exception is handled the code flow continues without program interruption.

try:

    #code

except ZeroDivisionError:

    #code

except TypeError:

    #code

except:

    #code

Raising Exceptions:

We can raise custom exceptions using the raise keuword.

try with else clause:

sometimes we want to run a piece of code when try was successful.

try:

    #code

except:

    #code

else:

    #code

try with finally:

python offers a finally clause which ensures execution of a piece of code irrespective of the exception.

try:

    #code

except:

    #code

finally:

#code

if __name__ = '__main__':

__name__ evaluates to the name of the module in python from where the program is run. if the module is being run directly from the cmd line the __name__ is set to string "__main__".

thus this behaviour is used to check if the module is run directly or imported to another file.

Global keyword:

global keyword is used to modify the variable outside of the current scope.

enumerate function:

It adds counter to an iterable and returns it.

for i,item in enumerate(list1):

    print(i,item)

list comprehensions:

It is an elegant way to create lists based on existing lists.

list1=[1,7,12,11,22]

list2=[i for item in list1 if item >8]


Practice:

Write a program to open 3 files 1.txt,2.txt and 3.txt.if any one of the files do not present then a message without exiting the program must be printed prompting the same.

def readFile(fileName):
    try:    
        with open(fileName,'r'as f:
            print(f.read())
    except:
        print(f"the file {fileName} does not exist")


readFile("1.txt")
readFile("2.txt")
readFile("3.txt")       


WAP to print 3rd,5th and 7th element from a list using enumerate function.

myList=[1,2,3,4,5,6,7,8,8,9,10]

for i,item in enumerate(myList):
    if i==2 or i==4 or i==6:
        print(f"the {i+1} element is {item}")


Write a list comprehension to print a list which contains the multiplication table of a user entered number.


numint(input("Please enter a number: "))

table = [num*i for i in range(1,11) ]
print(table)

WAP to display a/b  where a and b are integers. if b=0, display infinite by handling the ZeroDivisionError.

aint(input("Please enter 1st number: "))
bint(input("Please enter 2nd number: "))

try:
    print(a/b)
except ZeroDivisionError:
    print("Infinite")
except Exception as e:
    print(e)
finally:
    print("Thanks!")



No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...