Computer Science
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")
Answer
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both numbers entered were correct")
except ValueError: # 1 : to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # 2 : Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally: # 3 : to be executed at the end
print("JOB OVER... GO GET SOME REST")
Explanation
- When using
int(input("Enter the first number")) or int(input("Enter the second number")), the user is expected to input an integer. If the user enters a non-integer value (like a string or a floating-point number), a ValueError will be raised during the conversion to an integer. Theexcept ValueError:block is used to handle this situation by displaying a message asking the user to enter only numbers. - In the line
quotient = (num1 / num2), if num2 is entered as zero, it will lead to a ZeroDivisionError during the division operation (num1 / num2). Theexcept ZeroDivisionError:block is used to handle this scenario by displaying a message informing the user that the second number should not be zero. - The
finally:block is used to define code that should be executed regardless of whether an exception occurs or not.
Related Questions
Define the following:
- Exception Handling
- Throwing an exception
- Catching an exception
Explain catching exceptions using try and except block.
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.
What is the use of finally clause ? Use finally clause in the problem given in Question No. 7.