try and except
Catching Exceptions
Earlier when we used the input
and int
functions to read and parse an integer number entered by the user, there was a possibility of error if the user entered something which can’t be parsed into an int
. For eg, if the user entered some str
instead of an int
.
prompt = input("Enter your age\n")
try:
print (int(prompt))
except:
print('You should have entered a number')
First, the statements inside try
block are executed. If everything seems good, it skips the except
block and proceeds. If an exception (error) occurs in the try
block, Python jumps out of the try
block and executes the sequence of statements in the except block.
Handling an error with a try
statement is called catching an exception. In the above example, the except
statement prints the error message. In general, catching an exception gives us a chance to fix the problem, or try again, or at least end the program correctly.
Instructions
Define a function with name except_func
which takes one argument with name num
and returns its multiplication with itself. If the argument passed during the function call is not valid for multiplication, return a str
with content invalid number
.
def except_func(num):
try:
num1=int(num)
return num1*num1
except:
return “invalid number”
Function Call
except_func(“nishant”)