Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. # Exceptional - a different way to think about errors
  2. The rationale for this is to think about how we use exceptions and manage errors in code.
  3.  
  4. Imagine we have the below method that saves a piece of text to a database, which throws a checked exception:
  5. ```java
  6. public void save(String text) throws SaveFailureException {
  7. // ...
  8. }
  9. ```
  10.  
  11. In our client code, you are likely to witness something similar to the below:
  12. ```java
  13. try {
  14. save("something")
  15. } catch (SaveFailureException exception) {
  16. logger.error("Oh no", exception);
  17. }
  18. ```
  19.  
  20. 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
  21. that if we fail to write to write to the database we should write to a local file instead:
  22. ```java
  23. try {
  24. save("something")
  25. } catch (SaveFailureException exception) {
  26. logger.error("Oh no", exception);
  27. saveToLocalFile("something");
  28. }
  29. ```
  30. 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.
  31. 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.
  32.  
  33. Imagine if our code looked something like the below instead:
  34. ```java
  35. saveOrElse("something", (text) -> saveToLocalFile(text));
  36. ```
  37.  
  38. 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.
  39.  
  40. We can even include the logging if we really want to:
  41. ```java
  42. saveOrElse("something", (text) -> {
  43. logger.error("Oh no", exception);
  44. saveToLocalFile(text);
  45. });
  46. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement