More Related Content Similar to Definitive Guide to Working With Exceptions in Java - takj at Java Champions Conference (20) More from Victor Rentea (12) Definitive Guide to Working With Exceptions in Java - takj at Java Champions Conference1. 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. Victor Rentea
Blog, Talks, Goodies:
VictorRentea.ro
Independent Trainer
Founder of
Bucharest Software Craftsmanship Community
Java Champion
❤️ Simple Design, Refactoring, Unit Testing ❤️
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
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. 126 © VictorRentea.ro
a training by
We don't Recover
In web apps today, when handling exceptions,This talk is NOT
about library development
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. 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. 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. 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. 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. 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. 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)
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. 138 © VictorRentea.ro
a training by
Global Exception Handler
only catch
recoverable exceptions (if any)
Checked -> Runtime
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. 140 © VictorRentea.ro
a training by
Never Decapitate Your Exceptions !
} catch (SomeEx e) {
throw new AnotherEx("Oops");
}
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);
}
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
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
31. 151 © VictorRentea.ro
a training by
Optional<>
Customer.getMemberCard(): Optional<MemberCard>
entity for every nullable column
34. 154 © VictorRentea.ro
a training by
Java 8 Functional Interfaces
(eg Function, Predicate, ...)
+
checked exceptions
= pain
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. 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. 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. 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