AyO
AyO

Reputation: 23

Python - Not recognizing Exception Handling

So I am having problems with exception handling, I am running Python 3.6.3. this is my code:

txt = ""
txtFile = input("gimme a file.")
f = open(txtFile, "r")
try:    
    for line in f:
        cleanedLine = line.strip() 
        txt += cleanedLine
except FileNotFoundError:
    print("!")

So if I try and get an error with a bad input Instead of printing ! I still get the error:

Traceback (most recent call last):
File "cleaner.py", line 11, in <module>
    f = open(txtFile, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistentfile'

I have tried swapping in OSError, I have also tried just except:, which tells me that I am doing something wrong(because I shouldn't do that in the first place) and since I understand that except: should catch all of the exceptions.

Upvotes: -1

Views: 153

Answers (2)

Cleve Green
Cleve Green

Reputation: 779

Simple, you're opening something outside of the exception.

txt = []
txtFile = input("gimme a file.")
try:        
    f = open(txtFile, "r")
    for line in f.read().split('\n'):
        cleanedLine = line.strip()
        txt.append(cleanedLine)
except FileNotFoundError:
    print("!")

Upvotes: 1

Matt_G
Matt_G

Reputation: 516

Your try catch is encapsulating the loop through the lines.

The error is occurring when you are trying to open the file, outside of your try block.

Upvotes: 0

Related Questions