

class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast):
Exception.__init__(self) self.length = length self.atleast = atleast
try: s = raw_input('Enter something --> ')
if len(s) < 3:
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \ else: was expecting at least %d' % (x.length, x.atleast)
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
$ python raising.py
Enter something --> abc No exception was raised.
Here, we are creating our own exception type although we could've used any predefined exception/error for demonstration purposes. This new exception type is theShortInputException class. It has two fields length which is the length of the given input, andatleast which is the minimum length that the program was expecting.
In the except clause, we mention the class of error as well as the variable to hold the corresponding error/exception object. This is analogous to parameters and arguments in a function call. Within this particularexcept clause, we use thelength andatleast fields of the exception object to print an appropriate message to the user.