简体   繁体   中英

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.

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("!")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM