0

I got my little voice assistant in python, but I don't know what to do if wolframalpha doesn't give me any answer back.

elif 'wolfram' in command:
    try:
        print("I can answer your questions")
        talk("I can answer your questions")
        question = take_command()
        app_id = "XXXXXXXXXXXX"
        client = wolframalpha.Client(app_id)
        res = client.query(question)
        answer = next(res.results).text
        print(answer)
    except:
        print("Sorry, I can't answer that")
        talk("Sorry, I can't answer that")

It gives me these warnings

PEP 8: E722 do not use bare 'except'
Too broad exception clause

Erendil
  • 1
  • 2
  • You should explain what it's currently doing to "block the program from executing". Is there an exception? Is it just hanging forever? We can't really help unless we either know how the library works from past experience, or if we look it up, or if you just tell us, which is the easiest option. – Random Davis Dec 17 '20 at 20:34
  • I'd gander that `answer` isn't what you think. `StopIteration` throws when `next` fails. – Phix Dec 17 '20 at 22:27
  • Does this answer your question? [What is wrong with using a bare 'except'?](https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except) – wjandrea Dec 17 '20 at 23:38

1 Answers1

0

That is just a linter warning. To avoid it you can swallow the exception explicitly: remove the try...except block and run the code to find out what exception is being thrown, then catch it:

try:
    # ...code...
except NoAnswerException as ex:   # Or whatever is being thrown
    # ...handle exception gracefully

If you really want a catch-all, you can do except Exception as ex:. Note also that usually you want to have as little code as possible in the try block (ideally just one line) so you know which exceptions can be thrown and catch them explicitly.

bananafish
  • 2,877
  • 20
  • 29