Computer Science
What is the use of finally clause ? Use finally clause in the problem given in Question No. 7.
Python Exception Handling
1 Like
Answer
The statements inside the finally block are always executed, regardless of whether an exception has occurred in the try block or not. It is a common practice to use the finally clause while working with files to ensure that the file object is closed.
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
Output
Learning Exceptions...
Enter the first number: 12
Enter the second number: 4
3.0
Both numbers entered were correct
Great.. you are a good programmer
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: var
Please enter only numbers
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: 33
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
Answered By
1 Like
Related Questions
Define the following:
- Exception Handling
- Throwing an exception
- Catching an exception
Explain catching exceptions using try and except block.
Consider the code given below and fill in the blanks.
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 ...............: # to enter only integers print("Please enter only numbers") except ...............: # Denominator should not be zero print("Number 2 should not be zero") else: print("Great .. you are a good programmer") ...............: # to be executed at the end print("JOB OVER... GO GET SOME REST")You have learnt how to use math module in Class XI. Write a code where you use the wrong number of arguments for a method (say sqrt() or pow()). Use the exception handling process to catch the ValueError exception.