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
Output :
Yeah ! Your answer is : 1
I'm finally clause, always raised !!
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")