Reputation: 13
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
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
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
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
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