[Tutor] I need to ignore an error let the script continue to run

Jim jf_byrnes at comcast.net
Wed May 6 21:41:11 EDT 2020


On 5/6/20 2:44 AM, Alan Gauld via Tutor wrote:
> On 06/05/2020 01:36, Jim wrote:
>> On 5/5/20 4:13 PM, Mark Lawrence wrote:
> 
>>>> def parse_header(msg):
>>>>       with open('/home/jfb/' + email_msg, 'rb') as fp:
>>>>           header = BytesHeaderParser(policy=default).parse(fp)
>>>>           #  Now the header items can be accessed as a dictionary:
>>>>           try:
>>>>               username =  header['to'].addresses[0].username + '\n'
>>>>           except:
>>>
>>> Never use a bare except as in the long term it's asking for trouble,
>>> catch what you know can occur and let anything else raise it's own
>>> exception.
> 
>> I just write small scripts for my own use, so I really haven't had the
>> occasion to use try/except much. I'm sure your advice it correct in most
>> cases. I'm using try/except more like an 'if'. I needed some way to test
>> if certain items were  not in the header data being returned.
> 
> Where you are using try/except is not the issue, it is how.
> Mark is saying you should never use a "bare except", by which he means
> you should always specify the errors that you want to catch.
> In your case its a KeyERrror so you should have:
> 
>           try:
>              username =  header['to'].addresses[0].username + '\n'
>           except KeyError:
>              username = ' Blank \n'
> 
> The problem with your code is that it catches all errors (IOError,
> OSError, anything at all that may go wrong in the library
> function) and just blindly assigns 'blank'.
> 
> So you have no way of telling that something potentially serious
> has gone wrong. Something that may cause more errors further down
> your code, but you won't know where to look because the second
> error will now point at the wrong place.
> 
> That's why Mark is telling you not to use a bare except. He is not
> saying do not use try/except as a control mechanism, but just to
> always specify the errors you expect to occur. Allow unexpected
> ones to generate an error trace.
> 

OK thanks, I understand now.

Regards,  Jim



More information about the Tutor mailing list