Skip to main content

Why does the enum valueOf method throws an Exception

1 reply [Last post]
i30817
Offline
Joined: 2006-05-02

if the value is not recognized. This invalidates things like this code, that i was trying to use instead of nested ifs :

<br />
switch(TAG.valueOf(t.toString().toUpperCase())){<br />
                case HEAD : case TITLE :<br />
                    if(rememberTag){<br />
                        if (firstIgnorable == null)<br />
                            firstIgnorable = t;<br />
                        ignoreIt = true;<br />
                    }else if (t == firstIgnorable) {<br />
                        firstIgnorable = null;<br />
			ignoreIt = false;<br />
                    }<br />
                    break;<br />
                case I : case EM :<br />
                    StyleConstants.setItalic(memory, rememberTag);<br />
                    break;<br />
                case B :<br />
                    StyleConstants.setBold(memory, rememberTag);<br />
                    break;<br />
                case U :<br />
                    StyleConstants.setUnderline(memory, rememberTag);<br />
                    break;<br />
                case S : case DEL : case STRIKE :<br />
                    StyleConstants.setStrikeThrough(memory, rememberTag);<br />
                    break;<br />
            }<br />

As the valueOf method will throw an exception if the value of t is unknown, i guess i will use nested ifs, instead of defining the whole table of html (That may change in the future anyway). This wrapping of types in enums is probably a bad idea anyway...
Better use static import and nested ifs.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
forax
Offline
Joined: 2004-10-07

I don't see your point.
Why don't using a code like this one :
[code]
public TAG getTag(String tagname) {
try {
return TAG.valueOf(t.toString().toUpperCase());
} catch(IllegalArgumentException e) {
return null;
}
}
[/code]
and performs a null check.

Rémi Forax