0

We are trying to parse an xml file using sax parser, but we faced a problem using switch in :

 public void startElement(String uri, String localName, String qName,
    Attributes atts) throws SAXException {
    switch(MyEnum.valueOf(qNam))
     case tag1: 
          .......
                 break;
        case tag2:  
         ........
                 break;
        case tag5:  
         ..........

In each case we are populating some pojo objects.

The problem is when the parser encounter a tag that we are ignoring it throw an exception.

madhead
  • 31,729
  • 16
  • 153
  • 201
Majid Kamal
  • 363
  • 3
  • 7
  • 17

1 Answers1

0

Exception is thrown because your own code calls MyEnum.valueOf with argument that is not guaranteed to be name of enum constant.

Because you want to ignore Exception, it is likely better to not have exception thrown at all. That can be done for example by adding following method to MyEnum:

public static boolean isOneOfTheValues(String val) {
    for (MyEnum m: values()) {
        if (m.name().equals(val)) {
            return true;
        }
    }
    return false;
}

and then not going in to switch statement at all if it is known to be unknown value:

if (!MyEnum.isOneOfTheValues(s)) {
    return;
}
switch(MyEnum.valueOf(qNam))

If enumeration contains many constants, using rebuild set instead of iterating over return value of values() can provide better performance.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135