Search code examples
error-handlingsmalltalkvisualworks

Error handling when parsing XML file


I've got some code to parse an XML file like this:

[doc := (XML.XMLParser new) parse: aFilename asURI] on: XML.SAXParseException
    do: [:ex | MyCustomError raiseSignal: ex description].

I now want to handle the MyCustomError higher in the stack, by moving the XML file to a folder named 'Failed', but I get a sharing violation error because the parser has not had the opportunity to close the file.

If I alter my code like this it works, but I wonder if there is a better way:

[doc := (XML.XMLParser new) parse: aFilename asURI] on: XML.SAXParseException
        do: [:ex | description := ex description].
description ifNotNil: [MyCustomError raiseSignal: description].

Solution

  • Code can signal an exception for errors which are resumable (non-fatal); if you trap such an error you can't be certain that the XMLParser isn't intending to keep on going. For example, code that doesn't know whether it's being called in interactive or batch mode might signal an exception for a simple informational message; the caller would know whether to handle it in an interactive way (say with a message prompt) or a batch way (writing a message to a log file).

    In order for this to work the pieces of code that are communicating in this way have to know what sort of an error it is they're dealing with. (This would typically be done with a severity level, encoded either by state in the exception object or by raising a different class of exception.) If you inspect the ex object you might be able to see this information.

    In any case, the evidence suggests that XMLParser is treating SAXParseException as a resumable error (otherwise, it should clean up after itself). That being so, your "fix" seems appropriate enough.