How best to use exceptions?

Hi, I am currently writting a module for reading id3 v1, v1.1 & v2.x
tags. I figured the best way to learn was to rubyfying a playlist
generator I’d previously written in java.

I have a method for reading the tag data from the file. At present I am
asserting that certain conditions must exist i.e. the file must exist &
that the file is readable. (slightly reformated for posting)

def readTag(filename)
raise ArgumentError, “File does not exist”
unless FileTest.exist? filename
raise IOError, “File is not readable”
unless FileTest.readable? filename

<remainder ommited>

end

As the developer I know I can stipulate that this is how the module
should be used. A contract, as such, that says give me a real readable
file and I’ll get the tag data.

However is this the right / best / most sensible way to go about it?

Rob

If you are using your exceptions to generate error messages that the
user will see, then this seems reasonable, since sometimes the builtin
methods don’t give error messages that the user can understand. What
you have is unnecessary, though, since File.open will already raise an
exception if the file does not exist or is not readable.

Paul

···

On Thu, Sep 19, 2002 at 03:50:02AM +0900, Robert McGovern wrote:

def readTag(filename)
raise ArgumentError, “File does not exist”
unless FileTest.exist? filename
raise IOError, “File is not readable”
unless FileTest.readable? filename

end

If you are using your exceptions to generate error messages that the
user will see, then this seems reasonable, since sometimes the builtin
methods don’t give error messages that the user can understand. What
you have is unnecessary, though, since File.open will already raise an
exception if the file does not exist or is not readable.

Thanks for that Paul.

Out of interest where did you find that information? I can’t find
mention of that in either pickaxe or the 1.4 reference manual.
It would be helpful to know for the future.

Thanks again.

Rob

One source is the source itself.

Another is experience.

Perhaps the documentation should explain better what happens in error
conditions.

Paul

···

On Thu, Sep 19, 2002 at 05:30:14AM +0900, Robert McGovern wrote:

Out of interest where did you find that information? I can’t find
mention of that in either pickaxe or the 1.4 reference manual.
It would be helpful to know for the future.