Computer Science
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.
Python Exception Handling
4 Likes
Answer
Note — The TypeError
occurs when an incorrect number of arguments is provided for a function, while the ValueError
occurs when the number of arguments are correct but they contain inappropriate values. Hence, in the following code TypeError
is raised due to providing an incorrect number of arguments to the math.sqrt()
and math.pow()
function and it is handled using except
.
import math
try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)
try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)
Output
TypeError occurred with math.pow()
TypeError occurred with math.sqrt()
Answered By
2 Likes
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")
What is the use of finally clause ? Use finally clause in the problem given in Question No. 7.