Python Foundations - Assessments

27 / 54

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")

>>Enter your age
>>my age is twenty three

age = int(prompt)

As you try to convert the str into an int you receive an error,

ValueError: invalid literal for int() with base 10: 'my age is twenty three'

When any such error arises, the program stops immediately and doesn't execute any statements further.

Python provides us with a conditional structure to deal with these types of expected or unexpected errors called "try/except". Basically, if you know that certain statements in your program may encounter such errors, you may want to add some statements to be executed if an error occurs. These extra statements (the except block) are ignored if there is no error. Let's apply this conditional to the example discussed above,

 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.



Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...