0

How would I add exception handling to this while loop?

I've can't seem to wrap my head around it.

I've tried... Try: except: but to no avail.

Specifically this is a file selector. When the user doesn't select a file or selects the wrong filetype I want to keep the program open, let them know of the error and allow them to select a different file, rather than having the program quit.

while True:     
        
        event, values = window.read()

        if event in (sg.WIN_CLOSED, 'Cancel'):
                 break
                
        if event == '  Ok  ':
                 # If OK, then need to add the filename to the list of files and also set as the last used filename
                sg.user_settings_set_entry('-filenames-', list(set(sg.user_settings_get_entry('-filenames-', []) + [values['-FILENAME-'], ])))
                sg.user_settings_set_entry('-last filename-', values['-FILENAME-'])
                lastFile=values['-FILENAME-']
                break
        
        elif event == 'Clear History':
            sg.user_settings_set_entry('-filenames-', [])
            sg.user_settings_set_entry('-last filename-', '')
            window['-FILENAME-'].update(values=[], value='')
                      
window.close()

1 Answer 1

1

You should be able to use try/except within a while loop and have it exit or silence the exception as you would like. See this sample snipped below:

In [111]: while True:
     ...:     print('Hello')
     ...:     try:
     ...:         raise Exception()
     ...:     except Exception as e:
     ...:         print('Exception raised')
     ...:         raise e
     ...: 
Hello
Exception raised
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-111-c0ec85d9988a> in <module>
      5     except Exception as e:
      6         print('Exception raised')
----> 7         raise e
      8 

<ipython-input-111-c0ec85d9988a> in <module>
      2     print('Hello')
      3     try:
----> 4         raise Exception()
      5     except Exception as e:
      6         print('Exception raised')

Exception: 

Hope this helps!

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I have tried this... the problem is, I have break clauses and multiple if statements so I don't know how to arrange it all within my loop to ensure it works. Any ideas?
It would help if you posted a fuller example of what you're trying to build. You can definitely add a try/except to a while loop to exit when necessary, which answers your main question.
You're absolutely correct. I have got this working now. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.