问题
I need to add exception handling that considers if line 7 fails because there is no intersection between the query and array brands. I'm new to using exception handlers and would appreciate any advice or solutions.
I have written an example structure for exception handling, but I am not certain whether it will work.
brands = ["apple", "android", "windows"]
query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)
def brandSelector(query):
try:
brand = set(brands).intersection(query.split())
brand = ', '.join(brand)
return brand
except ValueError:
print("Brand does not exist")
# Redirect to main script to enter correct brand in query
回答1:
This is not the best way to do it, but it is a way.
def brandSelector(query):
try:
brand = set(brands).intersection(query.split())
brand = ', '.join(brand)
return brand
except ValueError:
print("Brand does not exist")
query = input("Enter your query: ").lower()
brandSelector(query)
brands = ["apple", "android", "windows"]
query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)
Your function is now recursive since it includes a call to itself. What happens is that if the try
throws an error, the except
gets triggered where the user is prompted to redefine the query. The function is then reran.
If no error is thrown by the intersection()
but instead an empty container is returned, you can do the following:
def brandSelector(query):
brand = set(brands).intersection(query.split())
brand = ', '.join(brand)
return brand
brands = ["apple", "android", "windows"]
brand = None
while not brand:
query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)
Which looks a lot like Tuan333's answer.
回答2:
When querying input from user, especially when you expect user to input bad data, I tend to put the querying function inside an infinite loop and break out when input data makes sense. As Ev. Kounis points out, there are many ways to do this. Here's a way I would do (untested code):
brands = ["apple", "android", "windows"]
def brandSelector(query):
try:
brand = set(brands).intersection(query.split())
brand = ', '.join(brand)
return brand
except ValueError:
print("Brand does not exist")
return None;
brand = None;
while brand is None:
query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)
So the condition where you can break out of the while
loop is when the input makes sense.
来源:https://stackoverflow.com/questions/39018875/exception-handler-to-check-if-inline-script-for-variable-worked