0

My Python code is getting stuck in a loop when I type "Exit" or "exit" after the program prompts me for a user name. Shouldn't it just exit the program altogether? What am I missing to make this actually exit when the user inputs this text rather than getting stuck in a loop? Thank you!

    while True:
        try:
            fname = input('Enter a file name: ')
            if fname.lower().strip() == 'exit':
                exit()
            else:
                fhand = open(fname) 
                break
        except:
            print(f'The file, {fname}, could not be located. Please enter another file name or type "Exit" to exit the application.')
            continue
    count = 0
    for line in fhand:
        print(line.rstrip().upper())
        count += 1
        if count > 4: break

I was expecting the program to exit when the user types "exit" in the prompt. Instead, it gets stuck in a loop (see screenshot).

  • 2
    `exit()` raises an exception, so the code lands up in its `except` block. See: https://stackoverflow.com/questions/25905923/python-sys-exit-not-working-in-try – slothrop Mar 05 '23 at 20:51
  • 4
    This is why you should never use a bare `except:` - it catches *everything*, including the SystemExit exception that is generated by `exit()`. Use a specific exception instead, `except FileNotFoundError:` perhaps. – jasonharper Mar 05 '23 at 20:51
  • This is my first time using Stack Overflow and this was incredibly helpful and fast. Thank you both @slothrop and @jasonharper! – The Tree Code Mar 05 '23 at 21:11
  • I honestly don't know why bare `except` was retained in Python 3. On the rare occasions you need to catch absolutely any exception, you can write `except BaseException` explicitly. No shortcut is warranted, IMO. – chepner Mar 05 '23 at 21:12

0 Answers0