python assigment - 6

 




2)Cleanup actions: Before leaving the try statement, “finally” clause is always executed, whether any exception is raised or not. These are clauses which are intended to define clean-up actions that must be executed under all circumstances.
Whenever an exception occurs and is not being handled by the except clause, first finally will occur and then the error is raised as default [Code 3].

Python Programs illustrating “Defining Clean Up Actions”

Code 1 : Code works normally and clean-up action is taken at the end

# Python code to illustrate
# clean up actions
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
    else:
        print("Yeah ! Your answer is :", result)
    finally:
        print("I'm finally clause, always raised !! ")
  
# Look at parameters and note the working of Program
divide(3, 2)

Output :

Yeah ! Your answer is : 1 

I'm finally clause, always raised !! 



3.



           




1)Raise an exception

 if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")
the raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")
Previous Post Next Post