At the end of this lesson, you will be able to:
B3.3 design algorithms to detect, intercept, and handle exceptions (e.g., division by zero, roots of negatives).
understand and use try..catch statements
With a paper and pencil, answer the following questions:
Give 1 example in daily life when you would use a select case (SWITCH) statement written in pseudocode. Make sure to include a default case.
Write the above example in pseudocode using an IF..ELSE IF..ELSE statement.
True or False: The latest version of Python 3 does not have an actual SWITCH statement.
Note: select (switch) case statements indentation -> case is indented, then indent the statements inside each case or default
// state the month selected as a string
switch (userMonth) {
case 1 :
std::cout << userMonth << " represents January. \n";
break;
case 2 :
std::cout << userMonth << " represents February. \n";
break;
default:
std::cout << "Error: " << userMonth << " does not represent a month. \n";
}
Python's equivalent is: match case
we will do a work-around function until match case is available to us in the updated version of Python Cloud9
from the online book Computer Based Problem Solving by Patrick Coxall, read:
in Python it is Try..Except
watch "Python Exception Handling"
exceptions are thrown when there is a run-time error in your code
exception handling is the process taken once an exception occurs
see the list of Built-In Python Exceptions
ValueError will detect a user input exception
in order to print what the user entered, you have to first assign it to a variable and THEN cast it to an int
try:
user_guess = input("Guess a number between 0 and 9: ")
user_guess_as_int = int(user_guess)
this will throw an exception IF the user enters a string
then you will be able to display what the user entered to the screen
recreate the "Number Guessing" program from Unit3-02
Use a random number generator to create a correct guess between 0 and 9 every time the program is started over.
Use an If..Then..Else so that the user is told if the number is correct or wrong. When they guess wrong, tell them the correct answer.
This time, make sure that the user is entering an Integer. If they do not enter an integer, inform them and do NOT let the program crash.
in groups of 2, do the following on the board for today's daily assignment:
Top-Down Design
Flow Chart
Pseudocode
Test Cases
complete the Daily Assignment section in Hãpara Workspace for this day
if Hãpara is not working, make a copy of this document
move it to your IMH-ICS folder for this course
recreate the same program in C++
refer to Unit3-03 to generate a random number
in C++ we use Try..Catch
// get the guess from the user as a string
...
try {
// convert the user's guess to an int
userGuessAsInt = std::stoi(userGuessAsString);
// check if the guess is correct
...
} catch (std::invalid_argument) {
// The user did not enter an integer.
std::cout << userGuessAsString << " is not an integer.\n";
}