java - Best way to handle exceptions that can not occur -
i use following code build sql statement updates values of fields specific object has. question is, since check if object has specific field exception can never occur. best way make code more readable example avoid using try {} catch {} block.
list<field> modelfields = arrays.aslist(model.getclass().getfields()); string updatestring = ""; (field field : fields) { if (modelfields.contains(field)) { try { updatestring += " " + field.get((object) model) + " "; } catch (illegalaccessexception e) { e.printstacktrace(); } } else { updatestring += " null "; } }
if think exception should never happen, throw runtime exception wrapping original exception:
try { updatestring += " " + field.get((object) model) + " "; } catch (illegalaccessexception e) { throw new illegalstateexception("this should never happen: field supposed public , accessible", e); }
that way, if you're wrong, or if code evolves , impossible becomes possible, you'll have exception clear error message , root cause of exception, instead of silently ignoring error , unrelated error later, or worse, valid, incorrect result.
Comments
Post a Comment