Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Exceptional - a different way to think about errors
- The rationale for this is to think about how we use exceptions and manage errors in code.
- Imagine we have the below method that saves a piece of text to a database, which throws a checked exception:
- ```java
- public void save(String text) throws SaveFailureException {
- // ...
- }
- ```
- In our client code, you are likely to witness something similar to the below:
- ```java
- try {
- save("something")
- } catch (SaveFailureException exception) {
- logger.error("Oh no", exception);
- }
- ```
- Above the client of the `save` method is handling the failure of not being able to save our text to a database. What if it is decided
- that if we fail to write to write to the database we should write to a local file instead:
- ```java
- try {
- save("something")
- } catch (SaveFailureException exception) {
- logger.error("Oh no", exception);
- saveToLocalFile("something");
- }
- ```
- From the above we can see that the writing to a local file appears three lines after the initial attempt to save it to the database.
- There is no reason for this other than the fact that we are using a try/catch block to handle this failure. Although we don't have to.
- Imagine if our code looked something like the below instead:
- ```java
- saveOrElse("something", (text) -> saveToLocalFile(text));
- ```
- So now we acknowledge that the `save` method can fail we instead provide `saveOrElse` which presents the client an opportunity to handle the failure and decide what they want to do. In order to do this, a function is provided by the client which takes the text to be saved as a parameter.
- We can even include the logging if we really want to:
- ```java
- saveOrElse("something", (text) -> {
- logger.error("Oh no", exception);
- saveToLocalFile(text);
- });
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement