Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

How To Raise Exceptions

Example 13.2. How to Raise Exceptions

#!/usr/bin/python
# Filename: raising.py

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:

raise ShortInputException(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)

print 'No exception was raised.'

Output

$ 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.

How It Works

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.