[Prev][Next][Index][Thread]

Re: Exceptions help please!



On Mon, 25 Sep 2000, Daniel Butun wrote:
> I found this on a website and was hoping that someone could help me with an
> exception for it.
> I've tried to work it out, but have been unable to identify it.
> The exception I'm after needs to catch invalid data like when a letter is
> used in the call to beer instead of a number.

You can find a list of condition classes in the DRM (last section of
Chapter 11), as pointed to on the www.gywdiondylan.org website in other
recent posts. In particular, the condition you want is "<type-error>".
See below for example usage ...

----------------------------------------------------------------

> // Dylan version of 99 Bottles of Beer
> // programmer: Jim Studt jim@federated.com
> 
> define method enumerate( count == 1 ) "1 bottle" end method enumerate;
> define method enumerate( count == 0 ) "no more bottles" end method
> enumerate;
> define method enumerate( count :: <integer> )
>   format-to-string("%d bottles", count);
> end method enumerate;
> 
> define method reference( count == 1) "it" end method reference;
> define method reference( count :: <integer>) "one" end method reference;
> 
> define method beer (argv0, #rest noise)
>   for ( i from argv0 to 1 by -1)     // I have modified this to argv0 from
> 99
>     format( *standard-output*, "%s of beer on the wall, %s of beer.\n",
>     enumerate(i), enumerate(i));
>     format( *standard-output*,
>     "  Take %s down, pass it around, %s of beer on the wall.\n",
>     reference(i), enumerate( i - 1));
>   end for;
> end method beer;

// I can't remember how "main" works in Gwydion Dylan -- I've more
// experience with Fun-Dev -- but I'm guessing it's better to do it this
// way than to modify "beer".
define method main (agrv0, #rest args)
  block ()
    beer(argv0);
  exception (error :: <type-error>)
    format(
      *standard-output*, "Error: %= has type %=, not type %=",
      error.type-error-value, error.type-error.value.object-class,
      error.type-error-expected-type);
  end;
end;

----------------------------------------------------------------

As it stands, however, I'd expect this to always succeed or always fail,
depending on the type of argv0 (which is probably <string>).  There's *no*
automatic type conversion in Dylan, so you probably need to do something
like this instead

----------------------------------------------------------------
define method main (agrv0, #rest args)
  block ()
    beer(string-to-integer(argv0));
  exception (error :: <type-error>)
    format(
      *standard-output*, "Error: %= has type %=, not type %=",
      error.type-error-value, error.type-error.value.object-class,
      error.type-error-expected-type);
  end;
end;
----------------------------------------------------------------

where string-to-integer is from the common-extensions module of the
common-dylan library.

HTH,
Hugh




References: