Last active
December 16, 2015 17:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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!"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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