Consider the program below, which modifies the BMI program to handle bad user input.
Of particular concern is the yellow-highlighted code, which is new branching logic added to the normal code, making the normal code flow of "get weight, get height, then print BMI" harder to see. Furthermore, the second check for negative values before printing the BMI is redundant and ripe for a programming error caused by inconsistency with the earlier checks (e.g., checking for <= here rather than just <).
The raise statement in the below program causes immediate exit from the try block and the execution of an exception handler. The exception handler prints the argument passed by the raise statement that brought execution there. The key thing to notice is that the normal code flow is not obscured via new if-else statements. You can clearly see that the flow is "get weight, get height, then print BMI".
except NameError: - an exception handler for NameError exceptions
except(ValueError, NameError): - an exception handler for ValueError and NameError exceptions
except: - a catch all exception handler
raiseValueError: causes a ValueError exception to occur
Note the clarity of the normal code, which obviously "gets the weight, gets the height, and prints the BMI" - the error checking code does not obscure the normal code.
Students also viewed
Sets found in the same folder
Other sets by this creator
a. A balance has the following size weights: , and . The number of and weights required to weigh an object weighing WEIGHT pounds can be calculated by using the following statements: // Determine the number of 100 lb weights w100 = int (WEIGHT/100) // Determine the number of 50 lb weights w50 = int ((WEIGHT - w Using these statements as a starting point, write a program that calculates the number of each type of weight needed to weigh a object. b. Without compiling or executing your program, manually check the effect of each statement in the program and determine what's stored in each variable as each statement is encountered. c. After verifying that your algorithm works correctly, compile and execute your program. Verify that the results your program produces are correct. After verifying that your program is working correctly, use it to determine the weights required to weigh a object.