[Tutor] general exception questions
Alan Gauld
alan.gauld at btinternet.com
Mon Oct 5 20:11:27 CEST 2015
On 05/10/15 18:46, richard kappler wrote:
> I'm reading up on exception handling, and am a little confused. If you have
> an exception that just has 'pass' in it, for example in a 'for line in
> file:' iteration, what happens? Does the program just go to the next line?
Yes, in your example it would ignore the exception and just move on to
the next line. Using continue would do the same and be more explicit.
If you do want to stop the loop use break.
> EX:
>
> for line in file:
> try:
> do something
> except:
> pass
>
> I know (so many of you have told me :-) that using pass is a bad idea,
Not necessarily, pass is fine in many situations.
The only problem is in situations where it's not
needed at all - then its better to just simplify
the construct. For example:
if some_test():
do_something()
else:
pass
is better written as just
if some_test():
do_something()
But something like:
class MyNewException(Exception): pass
is absolutely OK.
> how else do you skip the current line if the 'try' can't be done, and go on
> to the next line exiting the program with a trace error?
That last sentence confused me. If you use pass (or continue)
you will NOT get any trace error. If you want to store the
error to report it at the end then it's quite a bit more work,
you would need something like:
errors = []
for line in file:
try:
process(line)
except SomeError as e:
errors.append((line,e))
if errors:
for e in errors:
display_error(e)
where display_error() is an exercise for the student :-)
hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list