Lets assume i have a file named 'student.csv'.But in my python,I have mistakenly passed 'student1.csv' as file input,which does not exist.How to handle this exception to stop the execution further.
Asked
Active
Viewed 3.0k times
-3
-
1Just letting the program crash with a FileNotFoundError seems like a perfectly fine way to handle the exception. Execution of the program is stopped, exactly as desired; and anyone reading the stack trace knows exactly what the problem is. – Kevin Jul 12 '19 at 13:11
-
1use try -except block – Vinay Hegde Jul 12 '19 at 13:13
-
Possible duplicate of [File Open Function with Try & Except Python 2.7.1](https://stackoverflow.com/questions/8380006/file-open-function-with-try-except-python-2-7-1) – Dipesh Bajgain Jul 12 '19 at 13:13
-
@Kevin: Sure, 'cause nothing breeds confidence in an end user than seeing a stack trace. – Scott Hunter Jul 12 '19 at 13:13
-
@Kevin, for example, `open(nonexistent_file, 'w')` doesn't raise an exception, but creating a new file may not be desired, so this behavior may be considered an "exception". It's hard to tell what "exception" means in this context because unhandled exceptions _do_ stop the program's execution, which somehow isn't the case here – ForceBru Jul 12 '19 at 13:15
-
I am getting TypeError: 'NoneType' object is not iterable How to handle this exception – Saravanan Selvam Jul 12 '19 at 13:17
-
1@ScottHunter Don't think of it as user-hostile design; think of it as encouraging the user to learn the fundamentals of programming. Having to diagnose uncaught exceptions builds character ;-) – Kevin Jul 12 '19 at 13:18
2 Answers
9
Here is a working example, if the file is not found it will throw and FileNotFoundError
exception
try:
f = open('student.csv')
except FileNotFoundError:
print('File does not exist')
finally:
f.close()
print("File Closed")
Another Way:
try:
with open("student.csv") as f:
print("I will do some Magic with this")
except FileNotFoundError:
print('File does not exist')
Also If you dont want custom error message you can just use
with open("student.csv") as f:
print("I will do some Magic with this")
If the file does not exist you will still get an FileNotFoundErorr
example:
FileNotFoundError: [Errno 2] No such file or directory: 'student1.csv'

AutoTester213
- 2,714
- 2
- 24
- 48
-
2
-
6Even better: `with open('student.csv') as f:` and the file will close after the with block without having to add a `close()`. – Matthias Jul 12 '19 at 13:17
1
USe exception handling
:-
try:
file = open('student.csv')
except Exception as e:
print('File not found. Check the name of file.')

Rahul charan
- 765
- 7
- 15