[Tutor] exception classes

dman dsh8290@rit.edu
Tue, 1 Jan 2002 01:07:07 -0500


On Mon, Dec 31, 2001 at 08:51:23PM -0600, Kevin McCormick wrote:
| dman wrote:
| 
| >On Mon, Dec 31, 2001 at 01:15:28PM -0600, Kevin McCormick wrote:
| >| I am trying to figure out how to design an exception class
| >
| >What does your exception need to be able to do and what info does it
| >need to store?  The following is a minimal example :
| >
| ># first define the class
| >class MyException( Exception ) :
| >    pass
| 
| I have seen this where a block goes something like:
| 
| try:
|    <some operation>
| except:

This line means to catch all exceptions, regardless of type, but don't
assign that object to a name

|    raise MyException( 'error in some operation' )

then raise another exception.  The new exception contains some data,
which may (or, as in this case, may not) relate to the previous
exception.

| For example:
| 
|   class MyException( Exception ):
|       pass
| 
|   def f1(a, b, *var, **kw):
|       print a, b, var, kw
| 
|   try:
|       f1(1, 2, 34, 45, c=4, d=5, b=6)
|   except:
|       raise MyException('you made a boo-boo')
| 
| Gives result:
|   Traceback (most recent call last):
|     File "<stdin>", line 10, in ?
|   __main__.MyException: you made a boo-boo
| 
| Now, what do you do with it?

You have to catch it and do what you want with it.  If you are making
an application you need to determine what the proper response it -- it
may be to stop prematurely or it may be to report it to the user and
keep going.  Typically when creating a library you raise exceptions to
provide (error) information back to the client code (application) so
that it can properly handle the situations.

| I am writing a calendar type module of spreadsheet like functions, and I 
| want to return -1 for calls made with bad arguments, but give some 
| feedback, like -> error variable: x could not be processed, perhaps to a 
| log file or something.

In a language like C that lacks exceptions, returning -1 to indicate
failure is an acceptable practice.  It is bad practice in python.  In
python (or java or c++) you should raise (throw) an exception if an
error occures.  I don't remember the python name, but java has
IllegalArgumentException built-in that you can raise if the arguments
are bad.

| Also, as in my example, the Syntax Error was assigning 6 to b, where 2 
| was in the b slot.  How can information of this type be preserved?

Catch that SyntaxError exception and extract the message data from it,
than pack that data into the exception you subsequently raised.

-D

-- 

If any of you lacks wisdom, he should ask God, who gives generously to
all without finding fault, and it will be given to him.  But when he
asks he must believe and not doubt, because he who doubts is like a wave
of the sea, blown and tossed by the wind.
        James 1:5-6