The try...finally statement

In a situation where you are completely sure that a certain block of code will be executed whether the program throws exceptions or not, try...finally is useful. Consider the situation when you open a file and read the input, but for some reason the program throws an exception and the file you want is closed whether the exception occurs or not, then try...finally will solve the problem.

The syntax is as follows:

try:
#run this action first
except:
# Run if exception occurs
Finally :
#Always run this code

The order of the statement should be:

try -> except -> else -> finally

Let's discuss the code in finally1.py:

try: 
num = int(raw_input("Enter the number "))
re = 100/num
except:
print "Something is wrong"
else:
print "result is ",re
finally :
print "finally program ends"

In the preceding code, we used try, except, else, and finally blocks. Let's discuss the functionality by executing the code:

Output of finally1.py

In the preceding output, in the first run, 10 has been provided as the input and  try, else, and finally blocks have been executed. In the second run, a string Mohit has been supplied. Due to error in type conversion except and finally blocks have been executed.

With this you have seen the importance of the finally statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.80.101