Reputation: 2238
I'm reading a file and using try catch to catch cases where the data might not be the type that I'm looking for:
for w in text.readlines():
try:
new = float(w.split()[3].replace(',', '.'))
if new < temp and w.split()[1][3:5] == '12':
temp = new
date = w
except ValueError:
''
except IndexError:
''
This is really a hacky solution, not something that I would use, just something that I wrote because I needed access to some data quick. However, if I wanted to parse a very large file or stream, would such a solution (modified so that calls are made more intelligently etc) be viable, or should one opt for other solutions. My main question is regarding the performance of a try catch, is it an expensive operation, and are there guidelines for good uses of try-except? Hope this question is not too broad. In case it is, focus on my example.
Upvotes: 1
Views: 1255
Reputation: 5061
I can't say much about it as i am not expert but it is alwyas better to use try except
in any codeing languages where you seems that code may produce some error, and in python glossary
EAFP rule clearly says it.
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
for w in text.readlines():
try:
new = float(w.split()[3].replace(',', '.'))
if new < temp and w.split()[1][3:5] == '12':
temp = new
date = w
except ValueError:
Do Something
except IndexError:
Do Something
except Exception: #Exception is a Base class of all exceptions if any exception that isn't catch will go in it,
Do Something
Upvotes: 1
Reputation: 95712
In the particular example you give, you can easily test for and avoid the IndexError case, so I would do that test. The ValueError is harder to check for so you should catch the exception.
for w in text:
words = w.split()
if len(words) >= 4:
try:
new = float(words[3].replace(',', '.'))
if new < temp and words[1][3:5] == '12':
temp = new
date = w
except ValueError:
pass
Don't use readlines()
on a file, you should just iterate over the file instead.
A good rule of thumb when it is equally easy to check before or to handle an exception, is to consider how often the exception would be thrown. If in normal cases the exception triggers very rarely then just handle it, on the other hand if it will be a common case then it may be better to avoid throwing it. Since I know nothing about your data, I don't know what proportion of lines will have fewer than 4 fields, so in this case the choice is pretty arbitrary.
Upvotes: 1