1

I'm using pylint to review one of my .py scripts and the below warning shows:

W0703: Catching too general exception Exception (broad-except)

This is an extract of the code.

try:
    # Execute function1
    function1()
    logger.info('Function 1 successfully executed')
    
except Exception as e:
    send_mail_error(str(e))
    logger.error(str(e))

I would like to understand what is pylint suggesting here in order to improve it.

banana_99
  • 591
  • 5
  • 15

1 Answers1

2

It is good practice to catch specific exception, read here.

In your case you want to log unknown exception and send email. In such case I am using SMTPHandler and custom sys.excepthook - like this.

marcin
  • 517
  • 4
  • 23
  • Ok, so if I'm understanding correctly, instead of catching all exception, it's better practice to go one by one through Value Error, IO Error... and put a specific message for each? – banana_99 Jul 22 '21 at 14:57
  • 1
    Yes, it is. Read Blaze's comment under best answer of first question I linked. "... it's good to track down as many as you can and handle them appropriately and then have a backup catch all for the ones you miss." – marcin Jul 23 '21 at 09:24