1

Is there any way in Java to find out "who"/"what" threw the excpetion?

consider the following code which validates a couple of Textfields (which have certain constraint on what input is valid or not). I want to mark the corresponding textfield red.

public void validateInput() {
    try {
        textfieldName.validate();
        textfieldAge.validate();
    } catch (InvalidInputExcpetion e) {
        // Pseudocode
        // e.getThrower() would get me the reference to the Object which threw the exception
        (TextField e.getThrower()).markRed();
    }
}

The only solution I found is to extend my custom excpetion to hold a reference to the throwing textfield, isn't there an easier way?

Raphael Roth
  • 26,751
  • 15
  • 88
  • 145
  • Using a custom exception is the way to go here, since handling the exception is the same for all instances. – Kenney Jan 30 '16 at 16:21

2 Answers2

3

You can split your code in two try catch

public void validateInput() {
    try {
        textfieldName.validate();
    } catch (InvalidInputExcpetion e) {
        // Error in the textfieldName
        // Eventually return if you need to validate only one field if an error is thrown
    }
    try {
        textfieldAge.validate();
    } catch (InvalidInputExcpetion e) {
        // Error in the textfieldAge
    }
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

To prevent duplicating code, you can have validateInput take the text field as input, so it would validate one text field. Then call it for each text field.

public void validateInput(TextField textField) {
    try {
        textField.validate();
    } catch (InvalidInputExcpetion e) {
        // Handle Error in the textField
    }
}

Then call it for each TextField:

validateInput(textfieldName);
validateInput(textfieldAge);
DBug
  • 2,502
  • 1
  • 12
  • 25