Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
118 © VictorRentea.ro
a training by
The Definitive Guide to
Working with Exceptions in Java
victor.rentea@gmail.com ♦ ♦ @v...
Victor Rentea
Blog, Talks, Goodies:
VictorRentea.ro
Independent Trainer
Founder of
Bucharest Software Craftsmanship Commun...
Technical Training
400 days
(100+ online)2000 devs8 years
Training for you or your company: VictorRentea.ro
40 companies
P...
Clean Code
Refactoring
Clean Exception Handling
VictorRentea.ro122
A bit of history
123 © VictorRentea.ro
a training by
At the beginning
There were no functions
124 © VictorRentea.ro
a training by
At the beginning
There were no exceptions
125 © VictorRentea.ro
a training by
40 years ago, in C:
int errno = f(...);
The Age of Libraries
25y, Java: Checked vs Run...
126 © VictorRentea.ro
a training by
We don't Recover
In web apps today, when handling exceptions,This talk is NOT
about li...
127 © VictorRentea.ro
a training by
Checked Exceptions,
today
128 © VictorRentea.ro
a training by
code
129 © VictorRentea.ro
a training by
Diaper Anti-Pattern
} catch (Exception e) {
// TODO waste nights
}
a.k.a. Swallowing E...
130 © VictorRentea.ro
a training by
} catch (Exception e) {
// TODO waste nights
}
e.printStackTrace();IDE default code bl...
131 © VictorRentea.ro
a training by
throws
try
catch (Exception t) {/*surprise!*/}
RuntimeExceptions won the War !
because...
132 © VictorRentea.ro
a training by
Ignoring recurrent exception?
(eg. a poller)
log.trace(e.getMessage())
What to do with...
133 © VictorRentea.ro
a training by
} catch (SomeCheckedException e) {
}
} catch (SomeCheckedException e) {
log.error(e.ge...
134 © VictorRentea.ro
a training by
Legacy Code
Global Exception Handler
Logs and reports any unhandled exceptions
Core Lo...
135 © VictorRentea.ro
a training by
Presenting Errors to Users
What to show them?
Exception's message
int
enum
How to unit...
136 © VictorRentea.ro
a training by
code
137 © VictorRentea.ro
a training by
class MyException extends RuntimeException {
public enum ErrorCode {
GENERAL,
PHONE_AL...
138 © VictorRentea.ro
a training by
Global Exception Handler
only catch
recoverable exceptions (if any)
Checked -> Runtime
139 © VictorRentea.ro
a training by
Catch-Rethrow-with-Debug Pattern
➢ Check the logs above?
➢ Breakpoints?
Why? To find t...
140 © VictorRentea.ro
a training by
Never Decapitate Your Exceptions !
} catch (SomeEx e) {
throw new AnotherEx("Oops");
}
141 © VictorRentea.ro
a training by
4 Reasons to Catch-rethrow
User-friendly message
(code)
Tests
(code)
Developers
(rethr...
142 © VictorRentea.ro
a training by
The Boss Of All Exceptions
143 © VictorRentea.ro
a training by
145 © VictorRentea.ro
a training by
I've never seen you looking so lovely as you did tonight,
I've never seen you shine so...
147 © VictorRentea.ro
a training by
We CHARGE against it!
We don't defend against NULL
148 © VictorRentea.ro
a training by
We CHARGE against it!
We don't defend against NULL
Throw early
for constraints
return ...
149 © VictorRentea.ro
a training by
code
151 © VictorRentea.ro
a training by
Optional<>
Customer.getMemberCard(): Optional<MemberCard>
entity for every nullable co...
152 © VictorRentea.ro
a training by
You, defeating the Null
Customer.getMemberCard(): Optional<MemberCard>
153 © VictorRentea.ro
a training by
Java 8
154 © VictorRentea.ro
a training by
Java 8 Functional Interfaces
(eg Function, Predicate, ...)
+
checked exceptions
= pain
155 © VictorRentea.ro
a training by
code
156 © VictorRentea.ro
a training by
Higher-order
Functions!
Wrap checked exceptions in lambdas
Function<> Unchecked.functi...
157 © VictorRentea.ro
a training by
Try<>
Can hold either a result or an exception
Collect both results and exceptions in ...
158 © VictorRentea.ro
a training by
Key Points
• Use Runtime; @SneakyThrows; Unchecked for lambdas (jool)
• Anti-Patterns:...
159 © VictorRentea.ro
a training by
Further Reading, details and comments on this topic:
https://victorrentea.ro/blog/exce...
You’ve finished this document.
Download and read it offline.
Upcoming SlideShare
What to Upload to SlideShare
Next
Upcoming SlideShare
What to Upload to SlideShare
Next
Download to read offline and view in fullscreen.

Share

Definitive Guide to Working With Exceptions in Java - takj at Java Champions Conference

Download to read offline

A Pragmatic approach to work with exceptions in Java. Talk recording: https://www.youtube.com/watch?v=LRwCE7GreSM&feature=youtu.be

Discussing checked exceptions, Vavr, Lombok, and JooL library, Spring Framework and many more.

Supporting in-depth article series: https://victorrentea.ro/blog/exception-handling-guide-in-java/

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

Definitive Guide to Working With Exceptions in Java - takj at Java Champions Conference

  1. 1. 118 © 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 I wrote a series of articles with further details on this topic: https://victorrentea.ro/blog/exception-handling-guide-in-java/
  2. 2. Victor Rentea Blog, Talks, Goodies: VictorRentea.ro Independent Trainer Founder of Bucharest Software Craftsmanship Community Java Champion ❤️ Simple Design, Refactoring, Unit Testing ❤️
  3. 3. Technical Training 400 days (100+ online)2000 devs8 years Training for you or your company: VictorRentea.ro 40 companies Posting Good Stuff on: HibernateSpring Functional Prog Java PerformanceReactive Design Patterns Clean Code Refactoring Unit Testing any lang
  4. 4. Clean Code Refactoring Clean Exception Handling
  5. 5. VictorRentea.ro122 A bit of history
  6. 6. 123 © VictorRentea.ro a training by At the beginning There were no functions
  7. 7. 124 © VictorRentea.ro a training by At the beginning There were no exceptions
  8. 8. 125 © 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. 126 © 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. 127 © VictorRentea.ro a training by Checked Exceptions, today
  11. 11. 128 © VictorRentea.ro a training by code
  12. 12. 129 © VictorRentea.ro a training by Diaper Anti-Pattern } catch (Exception e) { // TODO waste nights } a.k.a. Swallowing Exceptions Shawarma-style Exception-Handling + Runtime bugs= catches all the sh*t
  13. 13. 130 © VictorRentea.ro a training by } catch (Exception e) { // TODO waste nights } e.printStackTrace();IDE default code block System.err might NOT be captured in your log file!
  14. 14. 131 © VictorRentea.ro a training by throws try catch (Exception t) {/*surprise!*/} RuntimeExceptions won the War ! because they don’t annoy us Why should I know about that IOException ?
  15. 15. 132 © VictorRentea.ro a training by Ignoring recurrent exception? (eg. a poller) log.trace(e.getMessage()) What to do with Checked Exceptions? } catch (SomeCheckedException e) { } throw new SomeRuntimeException(e); Wrap them in Runtimes Dynamicall lower log level via Spring Actuator or Logback JMX Bean
  16. 16. 133 © VictorRentea.ro a training by } catch (SomeCheckedException e) { } } catch (SomeCheckedException e) { log.error(e.getMessage(), e); } TERROR What if it slips unlogged ? Same exception logged multiple times Log-Rethrow Anti-Pattern Real Solution throw new SomeRuntimeException(e);
  17. 17. 134 © VictorRentea.ro a training by Legacy Code Global Exception Handler Logs and reports any unhandled exceptions Core Logic Only RuntimeExceptions allowed Checked -> Runtime old lib
  18. 18. 135 © 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 values set Never a Stack Trace: Security (OK for small apps)
  19. 19. 136 © VictorRentea.ro a training by code
  20. 20. 137 © VictorRentea.ro a training by class MyException extends RuntimeException { public enum ErrorCode { GENERAL, PHONE_ALREADY_REGISTERED, ... } private final ErrorCode code; private final Object[] params; ... } Translating Exceptions Any case not useful to users messages.properties GENERAL = Oups! PHONE_ALREADY_REGISTERED = The phone {0} is assigned to another user Checkatstartup _fr _ro _es
  21. 21. 138 © VictorRentea.ro a training by Global Exception Handler only catch recoverable exceptions (if any) Checked -> Runtime
  22. 22. 139 © VictorRentea.ro a training by Catch-Rethrow-with-Debug Pattern ➢ Check the logs above? ➢ Breakpoints? Why? To find the value of some key variable } catch (AEx e) { throw new BEx("Info " + id, e); } Must-Have Debugging an Exception AEx(
  23. 23. 140 © VictorRentea.ro a training by Never Decapitate Your Exceptions ! } catch (SomeEx e) { throw new AnotherEx("Oops"); }
  24. 24. 141 © VictorRentea.ro a training by 4 Reasons to Catch-rethrow User-friendly message (code) Tests (code) Developers (rethrow with debug message) Rethrow as Runtime @SneakyThrows (Lombok) for use-case fatal errors } catch (SomeEx e) { throw new RuntimeException(e); }
  25. 25. 142 © VictorRentea.ro a training by The Boss Of All Exceptions
  26. 26. 143 © VictorRentea.ro a training by
  27. 27. 145 © 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
  28. 28. 147 © VictorRentea.ro a training by We CHARGE against it! We don't defend against NULL
  29. 29. 148 © VictorRentea.ro a training by We CHARGE against it! We don't defend against NULL Throw early for constraints return Optional for "valid" nulls
  30. 30. 149 © VictorRentea.ro a training by code
  31. 31. 151 © VictorRentea.ro a training by Optional<> Customer.getMemberCard(): Optional<MemberCard> entity for every nullable column
  32. 32. 152 © VictorRentea.ro a training by You, defeating the Null Customer.getMemberCard(): Optional<MemberCard>
  33. 33. 153 © VictorRentea.ro a training by Java 8
  34. 34. 154 © VictorRentea.ro a training by Java 8 Functional Interfaces (eg Function, Predicate, ...) + checked exceptions = pain
  35. 35. 155 © VictorRentea.ro a training by code
  36. 36. 156 © VictorRentea.ro a training by Higher-order Functions! Wrap checked exceptions in lambdas Function<> Unchecked.function(CheckedFunction<> f) <dependency> <groupId>org.jooq</groupId> <artifactId>jool</artifactId> </dependency>
  37. 37. 157 © VictorRentea.ro a training by Try<> Can hold either a result or an exception Collect both results and exceptions in a single pass <dependency> <groupId>io.vavr</groupId> <artifactId>vavr</artifactId> </dependency>
  38. 38. 158 © VictorRentea.ro a training by Key Points • Use Runtime; @SneakyThrows; Unchecked for lambdas (jool) • Anti-Patterns: Diaper, Decapitation, Log-Rethrow • Global Exception Handler • Enum error codes for users or tests • Catch-Rethrow-with-Debug • Defeating NPE with early-throw, or Optional • Try (vavr) Further Reading, details and comments on this topic: https://victorrentea.ro/blog/exception-handling-guide-in-java/
  39. 39. 159 © VictorRentea.ro a training by Further Reading, details and comments on this topic: https://victorrentea.ro/blog/exception-handling-guide-in-java/ VictorRentea.ro Blog⭐, Company Training, Masterclasses, Best Talks,... victorrentea@gmail.com ¡¡ PLEASE !! Ask me anything! Training Topics: ▪ Clean Code + Refactoring ▪ Design Patterns ▪ Unit Testing + TDD ▪ Advanced FP with Java ▪ Spring ▪ Hibernate/JPA ▪ Reactive Programming ▪ Java Performance ▪ Pragmatic DDD
  • fccdinis

    Jun. 5, 2021
  • riadhmnasri

    Jan. 20, 2021

A Pragmatic approach to work with exceptions in Java. Talk recording: https://www.youtube.com/watch?v=LRwCE7GreSM&feature=youtu.be Discussing checked exceptions, Vavr, Lombok, and JooL library, Spring Framework and many more. Supporting in-depth article series: https://victorrentea.ro/blog/exception-handling-guide-in-java/

Views

Total views

450

On Slideshare

0

From embeds

0

Number of embeds

13

Actions

Downloads

47

Shares

0

Comments

0

Likes

2

×