0

I would like my program to exit regardless of the type of the exception that occurred. However, depending on the type of the exception, I want to log a different error message. How could I achieve this with less code repetitions? Following is the code I currently use:

try:
   <code>

except Exception1:    
    self.logger.exception('Error message 1')
    self.logger.error('Aborting')
    sys.exit()
except Exception2:
    self.logger.exception('Error message 2')
    self.logger.error('Aborting')
    sys.exit()
except Exception:
    self.logger.exception('Unexpected error')
    self.logger.error('Aborting')
    sys.exit()
c00der
  • 543
  • 1
  • 4
  • 20

3 Answers3

2
try:
    <code>
    err_msg = "" 
except Exception1:
    err_msg = 'Error message 1'
except Exception2:
    err_msg = 'Error message 2'
except Exception:
    err_msg = 'Unexpected error'

if err_msg != "":
    self.logger.exception(err_msg)
    self.logger.error('Aborting')
    sys.exit()
  • to the OP, the order of the Exception blocks is important. The most specific exceptions should always go on top; if `Exception` comes first, `Exception1` and `Exception2` will never be used – taylor swift Nov 29 '16 at 22:41
2

How about this?

try:
  <code>
except Exception as e:
  errMsg = ''
  if isinstance(e, Exception1):
    errMsg = 'Error message 1'
  elif isinstance(e, Exception2):
    errMsg = 'Error message 2'
  else:
    errMsg = 'Unexpected error'

  self.logger.exception(errMsg)
  self.logger.error('Aborting')
  sys.exit()
Robin Chow
  • 79
  • 3
1

You can define a function like this:

def exit_with_message(self, message):
    self.logger.exception(message)
    self.logger.error('Aborting')
    sys.exit()

And then for each exception call the function with message you like:

except Exception1:    
    self.exit_with_message('Error message 1')   
except Exception2:
    self.exit_with_message('Error message 2')
except Exception:
    self.exit_with_message('Unexpected error')
milorad.kukic
  • 506
  • 4
  • 11