You can raise exceptions using the raise statement - you specify the name of the error/exception and the exception object. The error or exception that you can raise should be a class which directly or indirectly is a derived class of the Error or Exception class respectively.
Example 13.2. Raising Exceptions
#!/usr/bin/python # Filename: raising.py class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): self.length = length self.atleast = atleast try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # Other work can go as usual here. except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException, x: print '\nThe input was of length %d, it should be at least %d'\ % (x.length, x.atleast) else: print 'No exception was raised.'
$ python raising.py Enter something --> Why did you do an EOF on me? $ python raising.py Enter something --> ab The input was of length 2, it should be atleast 3 $ python raising.py Enter something --> abc No exception was raised.
Here, we have created our own exception type, although we could've used any predefined exception/error for demonstration purposes. This new exception type is the class ShortInputException. It declares two fields - length and atleast which is the length of the input and the minimum length that the input should have been.
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. Inside this particular except clause, we use the length and atleast fields to print an appropriate message to the user.