More Related Content Similar to Definitive Guide to Working With Exceptions in Java (20) More from Victor Rentea (13) Definitive Guide to Working With Exceptions in Java1. 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. 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. 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. ... or for You:
victorrentea.teachable.com
victor.rentea@gmail.com
Training for your Company:
victorrentea.ro
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. 115 © VictorRentea.ro
a training by
We don't Recover
In web apps today, when handling exceptions,This talk is NOT
about library development
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. 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. 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. 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. 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. 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. 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
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. 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. 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. 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)
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
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
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
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. 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. 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. 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. 148 © VictorRentea.ro
a training by
Company Training: victorrentea@gmail.com For You: victorrentea.teachable.com
Questions or Follow: