I'm writing a small almost one method Java class for a job application and the advice given was to write it as though it was a piece of commercial software.
The processResult
method needs two string arguments of equal length. I thought the best thing to do is check that the args has at least 2 items, then inside the processResult
method check that the strings have the same length.
I am unsure about throwing a generic exception in my main method and then later using the try/catch statement. Is this a good practice to do? Would it be better practice to handle these as part of one try catch? Are custom Exceptions a good way to go for this type of problem?
Here is what I have at the moment.
public class Task {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
throw new Exception("Need 2 string arguments");
}
try {
int result = processResult(args[0], args[1]);
System.out.println(result);
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
private static boolean lengthsEqual(String a, String b) {
return Integer.compare(a.length(), b.length()) == 0;
}
private static int processResult(String inputOne, String inputTwo) {
if (!lengthsEqual(inputOne, inputTwo) {
throw new IllegalArgumentException("Strings must be the same length");
}
// method logic
return 0;
}
}