[Tutor] Getting the real exception clause
Mark Lawrence
breamoreboy at yahoo.co.uk
Sun Jun 16 22:52:16 CEST 2013
On 16/06/2013 21:26, Jim Mooney wrote:
> '''I'm using general Exception to print out what the exception is
> until I learn them, but
> it will print out "[Errno 2] No such file or directory" in this case,
> when the real
> exception I'd need to use in an except clause is FileNotFoundError.
> How do I get the
> exception I need to use in the except clause from the more English-like message?
> '''
>
> #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs
> try:
> fh = open('nosuchdirectory/text/truthyfalsey.txt')
> for line in fh:
> print(line,end='')
> fh.close()
> except Exception as err:
> print(err)
>
> Jim
> After indictment the bacon smuggler was put on the no-fry list
Easy, strip out the exception handling you have above.
c:\Users\Mark\MyPython>type a.py
with open('nosuchdirectory/text/truthyfalsey.txt') as fh:
for line in fh:
print(line,end='')
c:\Users\Mark\MyPython>a
Traceback (most recent call last):
File "C:\Users\Mark\MyPython\a.py", line 1, in <module>
with open('nosuchdirectory/text/truthyfalsey.txt') as fh:
FileNotFoundError: [Errno 2] No such file or directory:
'nosuchdirectory/text/truthyfalsey.txt'
A slight aside, note I've used the 'with' clause so there's no need to
explicity close the file, good ole Python does it for you.
--
"Steve is going for the pink ball - and for those of you who are
watching in black and white, the pink is next to the green." Snooker
commentator 'Whispering' Ted Lowe.
Mark Lawrence
More information about the Tutor
mailing list