I have been learning python for a couple of days now and am struggling with my "spirit". I am leaving school from C / C ++ / Java / Perl, and I understand that python is not C (in general), so I am trying to understand the spirit in order to make the most of it (and it’s still difficult) ...
My question is especially focused on handling and clearing exceptions: The code at the end of this post is intended to simulate a fairly common case of opening / parsing a file, where you need to close the file in case of an error ...
Most of the samples I've seen use the else clause from the try statement to close the file ... which made sense to me until I realized that the error could be caused
- opening itself (in this case there is no need to close the open file)
- parsing (in which if the file needs to be closed)
The catch here is that if you use the else clause from the try block, then the file never closes if an error occurs while parsing! On the other end, using the "finally" clause, you get the additional necessary verification, because the file_desc variable may not exist if an error occurred during opening (see comments in the code below) ...
This extra check is inefficient and full of crap, because any reasonable program can contain hundreds of characters and analyze the results of dir () - it's a pain in the ass ... Not to mention the lack of readability of such a statement ...
Most other languages allow variable definitions that can save the day here ... but in python everything seems implicit ...
file_desc, try/catch ... , ()... ... ... !
, ?
- / ? ?
- - try/except??? ?
- , file_desc, ... ???
- close()??? , ?
thanx ... :
class FormatError(Exception):
def __init__(self, message):
self.strerror = message
def __str__(self):
return repr(message)
file_name = raw_input("Input a filename please: ")
try:
file_desc = open(file_name, 'r')
while True:
current_line = file_desc.readline()
if not current_line: break
print current_line.rstrip("\n")
raise FormatError("oops... the file format is wrong...")
except FormatError as format_error:
print "The file {0} is invalid: {1}".format(file_name, format_error.strerror)
except IOError as io_error:
print "The file {0} could not be read: {1}".format(file_name, io_error.strerror)
else:
file_desc.close()
if 'file_desc' in dir():
print "The file exists and closed={0}".format(file_desc.closed)
else:
print "The file has never been defined..."
Lionel