10.4. *Exceptions as Strings

Prior to Python 1.5, standard exceptions were implemented as strings. However, this became limiting in that it did not allow for exceptions to have any relationships to each other. With the advent of exception classes, this is no longer the case. As of 1.5, all standard exceptions are now classes. It is still possible for programmers to generate their own exceptions as strings, but we recommend using exception classes from now on.

For backwards compatibility, it is possible to revert to string-based exceptions. Starting the Python interpreter with the command-line option -X will provide you with the standard exceptions as strings. This feature will be obsoleted beginning with Python 1.6.

If you must use string exceptions, we will now show you how to do it right. The following piece of code may or may not work:

# this may not work… risky!
try:
						:
						raise 'myexception'
           :
						except 'myexception'
     suite_to_handle_my_string_exception
						except:
						suite_for_other_exceptions
					

The reason why the above code may not work is because exceptions are based on object identity as opposed to object value (see Section 10.5.1). There are two different string objects above, both with the same value. To rectify the potential problem, create a static string object with which to use:

# this is a little bit better
myexception = 'myexception'
try:
						:
						raise myexception
           :
						except myexception:
     suite_to_handle_my_string_exception
						except:
						suite_for_other_exceptions
					

With this update, the same string object is used. However, if you are going to use this code, you might as well use an exception class. Substitute the myexception assignment above with:

# this is the best choice
class MyException(Exception):
      pass
						:
						try:
						:
						raise MyException
            :
						except MyException:
     suite_to_handle_my_string_exception
except:
						suite_for_other_exceptions

So you see, there really is no reason not to use exception classes from now on when creating your own exceptions. Be careful, however, because you may end up using an external module which may still have exceptions implemented as strings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset