ADavies00
ADavies00

Reputation: 13

Suspected parsing error in code using exit function

When I run this piece of code, I want the program to end after 'EASTER EGG' is printed. Instead the code breaks in try, except and prints 'file not found'. Can anyone help? Thanks.

finp=input('File name: ')
try:
    if finp=='easter egg':
        print('EASTER EGG')
        exit()
    else:
       file=open(finp,'r')
except:
    print('File not found. Please enter a valid file name.')
    exit()

Upvotes: 1

Views: 53

Answers (4)

Sivasankar Boomarapu
Sivasankar Boomarapu

Reputation: 188

import os

finp = input('File name: ')
try:
    if finp == 'easter egg':
        print('EASTER EGG')
        os._exit(1)
    else:
       file = open(finp,'r')
except:
    print('File not found. Please enter a valid file name.')
    os._exit(1)

Upvotes: 0

James
James

Reputation: 36691

Move the try/except block to encapsule only the file operations.

finp=input('File name: ')
if finp=='easter egg':
    print('EASTER EGG')
else:
    try:
        file = open(finp,'r')
    except FileNotFoundError as e:
        print('File not found. Please enter a valid file name.')
        exit()

Upvotes: 1

Vicrobot
Vicrobot

Reputation: 3988

exit() is raising SystemExit exception.

Thus the interpreter goes in the except block. The moment it gets in except block, it prints that message. And the program ends.

See here for docs referral.

Upvotes: 1

quamrana
quamrana

Reputation: 39404

It seems that exit() works by throwing an exception.

You should normally specify an exception type to catch in all except clauses, like this:

finp = input('File name: ')
try:
    if finp == 'easter egg':
        print('EASTER EGG')
        exit()
    else:
       file = open(finp,'r')
except FileNotFoundError:     # Added Exception type here
    print('File not found. Please enter a valid file name.')
    exit()

Upvotes: 2

Related Questions