0

When I use try/except and run it, it shows Process finished with exit code 0.

I use it on main.py and every function except for try/except functions properly.

import speech_recognition as sr

listener = sr.Recognizer()
try:
    with sr.Microphone() as source:
       print('listening..')
       voice = listener.listen(source)
       command = listener.recognize_google(voice)
       print(command)
except:
    pass

Screen shot of the page

Axe319
  • 4,255
  • 3
  • 15
  • 31
  • 4
    Please: no screenshot please. Copy past the output: it helps us much more, and it is also easier for people who look for the same error (and solution) – Giacomo Catenazzi Jan 20 '21 at 11:06
  • When you ask a question on stackoverflow, please add the code, input/output results in formatted text instead of screenshot. – Vijay Jan 20 '21 at 11:07
  • You are not printing anything in except block and silently 'pass' it. Have a look at https://stackoverflow.com/questions/1483429/how-to-print-an-exception-in-python – Vijay Jan 20 '21 at 11:17
  • try / except are not functions, but keywords or statements – TheEagle Jan 20 '21 at 11:30

1 Answers1

1

When I use try/except and run it, it shows Process finished with exit code 0.

That is normal behaviour : Every program emits an exit code when it exits. By default, that is 0, which means "Ok, everything went fine." Exit code 1 means about as much as "Oops, the date you entered is not a date". Exit code 2 is reserved for fatal errrors, such as "Oh no, i accidentally deleted all your photos !". For special cases, such as -11 for a Segmentation Fault, there are more exit codes, but as long as you are writing small python programs, there is no need to know about them.
So, as you catch the error if there were one, the exit code of your program will be 0, unless there is an uncatched error somewhere else in the code, or you manually change the exit code by calling sys.exit (note : this will also cause your program to exit immediately).
At the moment, you are catching the error, so your program will continue working, but you are not notifying the user that an error occurred. You should catch the error and then print it out, as in following example:

path = "/path/to/some/file"
try:
    f = open(path, "r") # try it with an existing and an inexisting file !
    print(f.read())
    f.close()
except FileNotFoundError as e: # handle non existing file
    print("Error: File", path, "not found")
except Exception as e: # handle all other errors
    print(e)

When you are handling all errors the same way, the second except block is enough.

TheEagle
  • 5,808
  • 3
  • 11
  • 39