Skip to content

Instantly share code, notes, and snippets.

@djleeds
Last active December 16, 2015 17:59
Show Gist options
  • Save djleeds/5474055 to your computer and use it in GitHub Desktop.
Save djleeds/5474055 to your computer and use it in GitHub Desktop.
One way to get around a need for a try/catch block, when you can change the code you're calling into. Doesn't apply in all situations.
// If you call records.find() with an id that doesn't exist, you get a RecordNotFound Exception
int id = 1;
try {
records.find(id).setName("Joe");
} catch(RecordNotFoundException e) {
System.out.println("Record wasn't found!");
}
// To get around the need for the try/catch, we could add a method to the records class to tell us ahead of time if it exists
// In this case, we add the method "has" to the records class, and call that first.
int id = 1;
if(records.has(id)) {
records.find(id).setName("Joe");
} else {
System.out.println("Record wasn't found!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment