Im kinda new to handling exceptions in Java with Junit, a little guidence would be much appreciated.
What I am trying to do:
-
I surround the creation of the new CustomObject with a
tryas the user can pass in aStringthat will not match anenumwhen we callvalueof(). I want to be able to catch an exception here, which I am, though I am told: “A catch statement that catches an exception only to rethrow it should be avoided.”. There must be a better way to handle this? -
If the new object has the correct
enumthen I callisValidObject, which returns aboolean. If theIntegeris not valid then Ithrowan exception. -
My test has a
@Test(expected = AssertionError.class)and is passing.
Is there a better/cleaner way to use the exceptions?
I have the code below:
private CustomObject getObjectFromString(String objectDataString) {
if (objectDataString != null) {
String[] customObjectComponents = objectDataString.split(":");
try {
CustomObject singleObject = new CustomObject(EnumObjectType.valueOf(customObjectComponents [0]),
Integer.parseInt(customObjectComponents [1]));
if (isValidCustomObject(singleObject)) {
return singleObject;
} else {
throw new IllegalArgumentException("Unknown custom object type/value: " + EnumObjectType.valueOf(customObjectComponents [0]) + ":"
+ Integer.parseInt(customObjectComponents [1]));
}
} catch (IllegalArgumentException e) {
throw e;
}
}
Oh, and if anyone can recommend anything good to read about exception handling, that would be great.
Yes, simply remove the try catch. Your code is equivalent to:
That code will throw an
IllegalArgumentExceptionif the value passed to yourenum.valueOf()is not valid or if yourisValidCustomObjectmethod returns false.Note that it might also throw an
IndexOutOfBoundExceptionif the string does not contain a:which you probably want to test before callingcustomObjectComponents[1]. And it might throw NumberFormatException too.And you seem to accept a null String as a valid entry, which is probably not a good idea (depends on your use case obviously).
I would probably have written it that way:
And finally, it would probably make sense for the CustomObject’s constructor to check whether its arguments are ok or not by itself, instead of having to call a separate isValid method. The last block would then simply be:
which would throw an IllegalArgumentException from the constructor if required.