Reputation: 391
I have a question: Is it possible to simplify these try catch?
Is it possible to only have one try catch and do the transformation in one catch? (Like "If ligne1 == null, ligne 1 = "", if pays == null, pays = "" etc...) Thank you very much :)
try {
ligne1 = lignes.item(0).getAttributes().item(0).getTextContent();
}catch (NullPointerException e){
ligne1 = "";
}
try{
ligne2 = lignes.item(1).getAttributes().item(0).getTextContent();
}catch (NullPointerException e){
ligne2 = "";
}
try{
ville = address.getElementsByTagName("city").item(0).getAttributes().item(0).getTextContent();
}catch (NullPointerException e){
ville = "";
}
try {
pays = address.getElementsByTagName("country").item(0).getAttributes().item(0).getTextContent();
}catch (NullPointerException e){
pays = "";
}
EDIT: The NullPointerException is thrown by item(0) if getElementsByTagName returns null. A solution could be to test if getElementsByTagName returns Null or not?
Upvotes: 1
Views: 141
Reputation: 285405
You should never do:
catch (NullPointerException e) {
//....
}
Don't do in a try/catch what should be done in an if/else. Instead why not simply create a method for this:
public String emptyIfNull(String input) {
return input == null ? "" : input;
}
ligne1 = emptyIfNull(lignes.item(0).getAttributes().item(0).getTextContent());
ligne2 = emptyIfNull(lignes.item(1).getAttributes().item(0).getTextContent());
ville = emptyIfNull(address.getElementsByTagName("city").item(0).getAttributes()
.item(0).getTextContent());
pays = emptyIfNull(address.getElementsByTagName("country").item(0).getAttributes()
.item(0).getTextContent());
Upvotes: 1