-1

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.

1
  • 3
    The error occurs before your try statement. Hence the error will not be caught. Commented Feb 1, 2018 at 15:12

2 Answers 2

1

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("!")
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

thanks, I am new to this, and I was misinterpreting the traceback .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.