exceptions_raise.py 655 B

123456789101112131415161718192021
  1. class ShortInputException(Exception):
  2. '''A user-defined exception class.'''
  3. def __init__(self, length, atleast):
  4. Exception.__init__(self)
  5. self.length = length
  6. self.atleast = atleast
  7. try:
  8. text = raw_input('Enter something --> ')
  9. if len(text) < 3:
  10. raise ShortInputException(len(text), 3)
  11. # Other work can continue as usual here
  12. except EOFError:
  13. print 'Why did you do an EOF on me?'
  14. except ShortInputException as ex:
  15. print ('ShortInputException: The input was ' + \
  16. '{0} long, expected at least {1}')\
  17. .format(ex.length, ex.atleast)
  18. else:
  19. print 'No exception was raised.'