'Exception handling in Python between backend and front end
As part of some study I am doing I am building a program with a frontend and backend module that is used to collect inputs from users. The program is functional but I now want to validate user entered data and gracefully handle exceptions without the program crashing. I've read a bit about different ways of doing this (i.e. try, except, finally) but would appreciate some guidance on the sample scenarios below which represent problems i'm trying to solve.
I need to handle this in a way where the frontend is the only module interacting with the user (i.e. no sys.stdout/sys.stdin to be in the backend). The backend should abstract as much of the processing of data and validation as possible before returning values/exceptions to the front end. Limitations are that I cannot use the print or input functions hence the use of sys, no for loops, need to handle this in as manual way as possible so I am learning the long way to help me transfer knowledge to other languages in future.
frontend module prompts the user down a list of questions
import sys
import backend
#must validate entry is string and equal to "Y" or "N"
sys.stdout.write("Would you like to buy a cake? Y/N")
likes_cake = backend.get_string(sys.stdin.readline())
#must validate entry is integer and greater than 1
sys.stdout.write("How many would you like to buy?")
buy_qty = backend.get_integer(sys.stdin.readline())
#must validate entry is float and great than 0
sys.stdout.write("How much are you willing to pay?")
buy_price = backend.get_float(sys.stdin.readline())
backend module
def get_string(entered_str):
return entered_str.upper().strip()
def get_integer(entered_int):
return int(entered_int)
def get_float(entered_float):
return float(entered_float)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
