I have to parse a String that can assume hex values or other non-hex values
0xff, 0x31 or A, PC, label, and so on.
I use this code to divide the two cases:
String input = readInput();
try {
int hex = Integer.decode(input);
// use hex ...
} catch (NumberFormatException e) {
// input is not a hex, continue parsing
}
Can this code be considered “ugly” or difficult to read? Are there other (maybe more elegant) solutions?
EDIT : I want to clarify that (in my case) a wrong input doesn’t exist: i just need to distinguish if it is a hex number, or not.
And just for completeness, i’m making a simple assebler for DCPU-16.
Exception handling is an integral part (and one of the design goals) of the Java programming language… you shouldn’t cast them off just because you think they are "ugly".
That said, if you want a simple and readable way to handle
NumberFormatExceptions, you might consider using theNumberUtilsclass instead.The
toInt(String str, int defaultValue)method converts aStringto anint, returning a default value if the conversion fails. If the string isnull, the default value is returned.The method encapsulates exception catching and handling, as seen in the source code below. As a result, the client only needs to make a single method call.