Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Definitive Guide to Working With Exceptions in Java

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige

Hier ansehen

1 von 38 Anzeige

Definitive Guide to Working With Exceptions in Java

Herunterladen, um offline zu lesen

Exceptions have been with us for 25 years in Java but have we learned to use them properly? Are checked exceptions a mistake? Should you use throw runtime or checked exceptions? And what to do with a checked exception, when you get one? And how to slay the boss of all exceptions: the NullPointerException.

Let’s put these old questions in the context of Java8+ lambdas, Vavr monads, Lombok, Spring, JAX-RS and other modern frameworks, and see the best practices of handling errors in Java today.Let’s put these old questions in the context of Java8+ lambdas, Vavr monads, Lombok, Spring, JAX-RS and other modern frameworks, and see the best practices of handling errors in Java today.

Exceptions have been with us for 25 years in Java but have we learned to use them properly? Are checked exceptions a mistake? Should you use throw runtime or checked exceptions? And what to do with a checked exception, when you get one? And how to slay the boss of all exceptions: the NullPointerException.

Let’s put these old questions in the context of Java8+ lambdas, Vavr monads, Lombok, Spring, JAX-RS and other modern frameworks, and see the best practices of handling errors in Java today.Let’s put these old questions in the context of Java8+ lambdas, Vavr monads, Lombok, Spring, JAX-RS and other modern frameworks, and see the best practices of handling errors in Java today.

Anzeige
Anzeige

Weitere Verwandte Inhalte

Diashows für Sie (20)

Ähnlich wie Definitive Guide to Working With Exceptions in Java (20)

Anzeige

Aktuellste (20)

Anzeige

Definitive Guide to Working With Exceptions in Java

  1. 1. 107 © VictorRentea.ro a training by The Definitive Guide to Working with Exceptions in Java victor.rentea@gmail.com ♦ ♦ @victorrentea ♦ VictorRentea.ro Code: https://github.com/victorrentea/exceptions-guide.git
  2. 2. Victor Rentea Clean Code Evangelist VictorRentea.ro/#playlist 100% Independent Trainer & Consultant Founder of Bucharest Software Craftsmanship Community Simple Design, Refactoring, TDD Java Champion 14 years of Java JS/TS PHP Scala C#, C++ Kotlin Join for free webinars: victorrentea.ro/community
  3. 3. Technical Training Hibernate/JPASpring Func Prog in Java & more 300+ days2000 devs8 years VictorRentea.rovictorrentea.teachable.com 40 companies Follow me: 30K 4K 3K Java PerformanceReactive-X Design Patterns DDD Clean Code Refactoring Unit Testing TDD any lang
  4. 4. ... or for You: victorrentea.teachable.com victor.rentea@gmail.com Training for your Company: victorrentea.ro
  5. 5. VictorRentea.ro111 A bit of history
  6. 6. 112 © VictorRentea.ro a training by At the beginning There were no functions
  7. 7. 113 © VictorRentea.ro a training by At the beginning There were no exceptions
  8. 8. 114 © VictorRentea.ro a training by 40 years ago, in C: int errno = f(...); The Age of Libraries 25y, Java: Checked vs Runtime 35y, C++: Invisible exceptions
  9. 9. 115 © VictorRentea.ro a training by We don't Recover In web apps today, when handling exceptions,This talk is NOT about library development
  10. 10. 116 © VictorRentea.ro a training by Checked Exceptions
  11. 11. 117 © VictorRentea.ro a training by code
  12. 12. 118 © VictorRentea.ro a training by Diaper Anti-Pattern } catch (Exception e) { // TODO waste nights } a.k.a. Exception Swallowing Shawarma-style Exception-Handling Including Runtime bugs= catches all the sh*t
  13. 13. 119 © VictorRentea.ro a training by throws try catch (Exception t) {/*surprise!*/} RuntimeExceptions won the War ! (except for recoverable? errors thrown by libraries) because we don’t see them Why should I know about that IOException ?
  14. 14. 120 © VictorRentea.ro a training by } catch (SomeCheckedException e) { throw new SomeRuntimeException(e); } Ignore recurrent exception? (eg. a file poller) log.trace(e.getMessage())
  15. 15. 121 © VictorRentea.ro a training by } catch (SomeCheckedException e) { throw new SomeRuntimeException(e); } } catch (SomeCheckedException e) { throw new SomeRuntimeException(e); } e.printStackTrace();log.error(e.getMessage(), e); System.err might NOT be logged!
  16. 16. 122 © VictorRentea.ro a training by } catch (SomeCheckedException e) { throw new SomeRuntimeException(e); } TERROR What if no one logs it? Same exception logged multiple times Log-Rethrow Anti-Pattern Real Solution log.error(e.getMessage(), e);
  17. 17. 123 © VictorRentea.ro a training by Legacy Code Global Exception Handler Logs and reports any unhandled exceptions Core of Your App Only RuntimeExceptions allowed Checked -> Runtime old lib
  18. 18. 124 © VictorRentea.ro a training by Presenting Errors to Users What to show them? Exception's message int enum How to unit-test that? How about MVC? Not developer-friendly Finite-set Never a Stack Trace: Security
  19. 19. 125 © VictorRentea.ro a training by code
  20. 20. 126 © VictorRentea.ro a training by class YourException extends RuntimeException { public enum ErrorCode { GENERAL, PHONE_ALREADY_REGISTERED, ... } private final ErrorCode code; private final Object[] params; ... } Error Messages Any case not required to report messages.properties GENERAL = Oups! PHONE_ALREADY_REGISTERED = The phone {0} is assigned to another user Checkatstartup _fr _ro _es
  21. 21. 127 © VictorRentea.ro a training by Global Exception Handler Logs and reports any unhandled exceptions selectively catch only recoverable cases (x-rare) Checked -> Runtime = the only valid reason for creating more exception types Keep Stack Traces from reaching the UI/API
  22. 22. 128 © VictorRentea.ro a training by Catch-Rethrow-with-Debug Pattern ➢ Searching for hints in the log above? ➢ Breakpoints? Why? To find the value of some variable. } catch (AEx e) { log.error("Debug info " + id); throw new BEx(e); } } catch (AEx e) { throw new BEx("Info " + id, e); } Must-Have Never decapitate the exceptions! Debugging an Exception
  23. 23. 129 © VictorRentea.ro a training by 4 Reasons to Catch-rethrow User-visible exceptions (code) Tests (code) Developers (+debug info) Wrapping a Checked (into a runtime) @SneakyThrows (Lombok lib)
  24. 24. 131 © VictorRentea.ro a training by The Queen Of All Exceptions
  25. 25. 132 © VictorRentea.ro a training by
  26. 26. 133 © VictorRentea.ro a training by I've never seen you looking so lovely as you did tonight, I've never seen you shine so bright, I've never seen so many men ask you if you wanted to dance, Looking for a little romance, given half a chance, And I have never seen that dress you're wearing, Or the highlights in your hair that catch your eyes, I have been blind; = P1 production Incident The Lady In Redby Chris De Burgh = on-call bug = unsolved for years = spend the night with you = although they lack the knowledge/skills = 50-lines stack-trace = the DEBUG logs before it N P E
  27. 27. 135 © VictorRentea.ro a training by ➔ Useful message in Java 15
  28. 28. 136 © VictorRentea.ro a training by NPE How do you fight it ? Throw early Optional
  29. 29. 138 © VictorRentea.ro a training by Optional<> For functions that might not return anything
  30. 30. 139 © VictorRentea.ro a training by You, defeating the Null Monster Customer.getMemberCard(): Optional<MemberCard> Entity Getters returning Optional for NULLABLE fields of an Entity
  31. 31. 140 © VictorRentea.ro a training by Java 8
  32. 32. 142 © VictorRentea.ro a training by Java 8 Functional Interfaces (eg Function, Predicate, ...) don't declare any checked exceptions. Methods throwing checked are painful to use with Stream API
  33. 33. 143 © VictorRentea.ro a training by code
  34. 34. 144 © VictorRentea.ro a training by Mmm.. Higher-order Functions! Convert functions to Rethrow as Runtime Function<..> Unchecked.function(CheckedFunction<..> f) (jOOL lib)
  35. 35. 145 © VictorRentea.ro a training by Try<>(vavr lib) Can hold either a result or an exception Use to collect both results and exceptions in one pass
  36. 36. 146 © VictorRentea.ro a training by Key Points • Use Runtime; @SneakyThrows; Unchecked (jool) • Anti-Patterns: Diaper and Log-Rethrow • Enum error codes for users or tests • Global Exception Handler • Catch-Rethrow-with-Debug • Defeating NPE with early-throw, or Optional • Try (vavr) ➔ my 'Functional Design Patterns' talk at Devoxx Belgium
  37. 37. 147 © VictorRentea.ro a training by Left-Over • Async exceptions (Executors, @Async, CompletableFuture, Reactive-X) • finally {throw} • AutoCloseable.close() {throw} –> Suppressed Exceptions – link • throw before mutating object state • Don't use exceptions for flow control (as a GOTO statement) • InterruptedException – link • Sealed classes + records + Switch Template Matching Java 16+
  38. 38. 148 © VictorRentea.ro a training by Company Training: victorrentea@gmail.com For You: victorrentea.teachable.com Questions or Follow:

×