Reputation: 75
I want to write a file log with the errors of a method that reads from a xml file. This method is too large, and I want to control the line content that causes an error. Now I have a variable that has the field I'll going to read and If this field fails the method return the error with this field's name. It's a bad solution, and I need something similar but more dynamic.
String error;
...
error= name;
String name = getValue("name");
error= surname;
String surname = getValue("surname");
......
catch(Exception){
return error;
}
Upvotes: 1
Views: 75
Reputation: 49606
Yes, it's a terrible idea.
You save "name"
into the error
variable prior to reading the property. You have no idea if the property will be read but the variable has been set regardless of the read. If every property has been parsed successfully, which is what we hope for, you still will have the error variable set to some property name.
In such scenarios, we usually put this information into an exception instance. When we are in a catch block, we are able to access that information and act accordingly.
public String getValue(String propertyName) {
try {
tryToReadProperty(propertyName);
} catch (Exception e) {
// something wrong happened
throw new IllegalArgumentException(propertyName);
}
}
...
try {
String name = getValue("name");
String surname = getValue("surname");
} catch (IllegalArgumentException e){
String error = e.getMessage();
}
I used IllegalArgumentException
for the sake of simplicity, it should be replaced with a more meaningful domain-specific exception type.
return error;
We rarely do that. Instead, we propagate an exception or rethrow a different layer-determined exception.
Upvotes: 1