Q.What is the use of finally clause? Use finally clause in the problem given in Question No. 7.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The finally clause guarantees that a block of code runs no matter what happens in the try/except/else chain above it. Applied to Question 7's own program, its finally: print(" JOB OVER... GO GET SOME REST") block is what makes that final message print on every single run of the program.
Understanding the finally clause
The try statement can have an optional finally clause. Statements written inside finally always execute, regardless of whether an exception occurred in the try block, and regardless of whether that exception was handled by an except clause. This is exactly why finally is commonly used for cleanup work — such as closing a file — that must happen no matter what.
If a finally clause is used, it must be the last clause of the try statement, after every except block and after the optional else clause.
Question 7's program
Question 7 asks you to fill in the blanks of this program, and the correct blanks are ValueError, ZeroDivisionError, and finally:
print(" Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1/num2)
print("Both the numbers entered were correct")
except ValueError: # to enter only integers
print(" Please enter only numbers")
except ZeroDivisionError: # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
finally: # to be executed at the end
print(" JOB OVER... GO GET SOME REST")
Question 9 asks specifically for the finally clause to be used in this program — which the fill-in-the-blanks answer to Question 7 already supplies as its third blank. The finally block is:
finally:
print(" JOB OVER... GO GET SOME REST")
Tracing all three cases
-
Non-integer input (e.g., the user types
"abc"fornum1ornum2):int()raisesValueError. The firstexceptblock catches it and prints" Please enter only numbers". Because an exception occurred,elseis skipped.finallystill runs, printing" JOB OVER... GO GET SOME REST". -
Zero as the second number: both inputs convert to integers successfully, but
num1/num2raisesZeroDivisionError. The secondexceptblock catches it and prints" Number 2 should not be zero". Againelseis skipped, andfinallystill runs. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.