A Byte of Python

Raising Exceptions

You can raise exceptions using the raise statement. You also have to specify the name of the error/exception and the exception object that is to be thrown along with the exception. The error or exception that you can arise should be class which directly or indirectly is a derived class of the Error or Exception class respectively.

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, \
		was expecting at least %d' % (x.length, x.atleast)
else:
	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 the ShortInputException class. It has two fields - length which is the length of the given input, and atleast 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 particular except clause, we use the length and atleast fields of the exception object to print an appropriate message to the user.