How to know which variable is the culprit in try block?

You are having an XY-Problem.

You don’t want to read the actual variable name. You want to be able to validate input and give reasonable error messages to your user.

String fileName, maxLengthInput, minLengthInput;
int maxLength, minLength;

List<String> errors = new ArrayList<>();

try {
    maxLength = Integer.parseInt(maxlengthInput);
} catch (NumberFormatException nfe) {
    errors.add("Invalid input for maximum length, input is not a number");

try {
    minLength = Integer.parseInt(minlengthInput);
} catch (NumberFormatException nfe) {
    errors.add("Invalid input for minimum length, input is not a number");

// show all error strings to the user

Not throwing the exceptions directly but collecting them allows you to notify the user about all invalid inputs at once (maybe highlight the related fields with red color) instead of having them fix one input, trying to submit again, and then to see that another input is also wrong.

Instead of Strings you could user your own data struture containing information of the related field etc., but that quickly gets out of scope. The main gist is: use two try-catch blocks, and you are able to differentiate which field is errorneous.

If more inputs are involved, you can refactor this into a loop.

Leave a Comment