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.