SlideShare a Scribd company logo
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
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
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
... or for You:
victorrentea.teachable.com
victor.rentea@gmail.com
Training for your Company:
victorrentea.ro
VictorRentea.ro111
A bit of history
112 © VictorRentea.ro
a training by
At the beginning
There were no functions
113 © VictorRentea.ro
a training by
At the beginning
There were no exceptions
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
115 © VictorRentea.ro
a training by
We don't Recover
In web apps today, when handling exceptions,This talk is NOT
about library development
116 © VictorRentea.ro
a training by
Checked Exceptions
117 © VictorRentea.ro
a training by
code
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
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 ?
120 © VictorRentea.ro
a training by
} catch (SomeCheckedException e) {
throw new SomeRuntimeException(e);
}
Ignore recurrent exception?
(eg. a file poller)
log.trace(e.getMessage())
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!
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);
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
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
125 © VictorRentea.ro
a training by
code
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
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
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
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)
131 © VictorRentea.ro
a training by
The Queen Of All Exceptions
132 © VictorRentea.ro
a training by
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
135 © VictorRentea.ro
a training by
➔ Useful message in Java 15
136 © VictorRentea.ro
a training by
NPE
How do you fight it ?
Throw early
Optional
138 © VictorRentea.ro
a training by
Optional<>
For functions that might not return anything
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
140 © VictorRentea.ro
a training by
Java 8
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
143 © VictorRentea.ro
a training by
code
144 © VictorRentea.ro
a training by
Mmm..
Higher-order
Functions!
Convert functions to
Rethrow as Runtime
Function<..> Unchecked.function(CheckedFunction<..> f)
(jOOL lib)
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
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
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+
148 © VictorRentea.ro
a training by
Company Training: victorrentea@gmail.com For You: victorrentea.teachable.com
Questions or Follow:

More Related Content

PDF
Unit Testing like a Pro - The Circle of Purity
PDF
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
PDF
Don't Be Mocked by your Mocks - Best Practices using Mocks
PDF
Integration testing with spring @JAX Mainz
PPTX
Clean Code with Java 8 - Functional Patterns and Best Practices
PDF
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
PDF
The Art of Unit Testing - Towards a Testable Design
PDF
Clean Lambdas & Streams in Java8
Unit Testing like a Pro - The Circle of Purity
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Don't Be Mocked by your Mocks - Best Practices using Mocks
Integration testing with spring @JAX Mainz
Clean Code with Java 8 - Functional Patterns and Best Practices
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Art of Unit Testing - Towards a Testable Design
Clean Lambdas & Streams in Java8

What's hot (20)

PDF
Integration testing with spring @snow one
PDF
Pure Functions and Immutable Objects
PPTX
Functional Patterns with Java8 @Bucharest Java User Group
PDF
Hibernate and Spring - Unleash the Magic
PPTX
Clean Code - The Next Chapter
PPTX
Clean Pragmatic Architecture - Avoiding a Monolith
PDF
Pure functions and immutable objects @dev nexus 2021
PDF
Clean pragmatic architecture @ devflix
PDF
TDD Mantra
PDF
Refactoring Games - 15 things to do after Extract Method
PDF
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
PDF
Refactoring blockers and code smells @jNation 2021
PDF
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
PDF
Extreme Professionalism - Software Craftsmanship
PPTX
Spring @Transactional Explained
ZIP
Test
PDF
Java fx smart code econ
PDF
Pharo Optimising JIT Internals
KEY
Working Effectively With Legacy Code
ODP
Automated testing in Python and beyond
 
Integration testing with spring @snow one
Pure Functions and Immutable Objects
Functional Patterns with Java8 @Bucharest Java User Group
Hibernate and Spring - Unleash the Magic
Clean Code - The Next Chapter
Clean Pragmatic Architecture - Avoiding a Monolith
Pure functions and immutable objects @dev nexus 2021
Clean pragmatic architecture @ devflix
TDD Mantra
Refactoring Games - 15 things to do after Extract Method
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Refactoring blockers and code smells @jNation 2021
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Extreme Professionalism - Software Craftsmanship
Spring @Transactional Explained
Test
Java fx smart code econ
Pharo Optimising JIT Internals
Working Effectively With Legacy Code
Automated testing in Python and beyond
 
Ad

Similar to Definitive Guide to Working With Exceptions in Java (20)

PDF
Java - Exception Handling Concepts
PPT
JP ASSIGNMENT SERIES PPT.ppt
PPTX
Chapter v(error)
DOCX
Unit5 java
PPT
Exception Handling.ppt
DOCX
MODULE5_EXCEPTION HANDLING.docx
PPTX
Exception handling and throw and throws keyword in java.pptx
PPT
PPTX
Exception handling
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception handling in java
PDF
Design byexceptions
Java - Exception Handling Concepts
JP ASSIGNMENT SERIES PPT.ppt
Chapter v(error)
Unit5 java
Exception Handling.ppt
MODULE5_EXCEPTION HANDLING.docx
Exception handling and throw and throws keyword in java.pptx
Exception handling
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception handling in java
Design byexceptions
Ad

More from Victor Rentea (18)

PDF
Top REST API Desgin Pitfalls @ Devoxx 2024
PDF
The Joy of Testing - Deep Dive @ Devoxx Belgium 2024
PDF
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
PDF
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
PDF
Microservice Resilience Patterns @VoxxedCern'24
PDF
Distributed Consistency.pdf
PDF
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
PDF
Testing Microservices @DevoxxBE 23.pdf
PPTX
From Web to Flux @DevoxxBE 2023.pptx
PPTX
Test-Driven Design Insights@DevoxxBE 2023.pptx
PDF
Profiling your Java Application
PPTX
OAuth in the Wild
PPTX
The tests are trying to tell you [email protected]
PPTX
Vertical Slicing Architectures
PDF
Software Craftsmanship @Code Camp Festival 2022.pdf
PDF
Unit testing - 9 design hints
PPTX
Extreme Professionalism - Software Craftsmanship
PDF
Clean architecture - Protecting the Domain
Top REST API Desgin Pitfalls @ Devoxx 2024
The Joy of Testing - Deep Dive @ Devoxx Belgium 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Microservice Resilience Patterns @VoxxedCern'24
Distributed Consistency.pdf
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Testing Microservices @DevoxxBE 23.pdf
From Web to Flux @DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
Profiling your Java Application
OAuth in the Wild
The tests are trying to tell you [email protected]
Vertical Slicing Architectures
Software Craftsmanship @Code Camp Festival 2022.pdf
Unit testing - 9 design hints
Extreme Professionalism - Software Craftsmanship
Clean architecture - Protecting the Domain

Recently uploaded (20)

PDF
Nekopoi APK 2025 free lastest update
PPTX
history of c programming in notes for students .pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
assetexplorer- product-overview - presentation
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
System and Network Administration Chapter 2
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Nekopoi APK 2025 free lastest update
history of c programming in notes for students .pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Understanding Forklifts - TECH EHS Solution
Odoo POS Development Services by CandidRoot Solutions
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Navsoft: AI-Powered Business Solutions & Custom Software Development
assetexplorer- product-overview - presentation
L1 - Introduction to python Backend.pptx
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
How to Choose the Right IT Partner for Your Business in Malaysia
Design an Analysis of Algorithms II-SECS-1021-03
Why Generative AI is the Future of Content, Code & Creativity?
System and Network Administration Chapter 2
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...

Definitive Guide to Working With Exceptions in Java

  • 1. 107 © VictorRentea.ro a training by The Definitive Guide to Working with Exceptions in Java [email protected] ♦ ♦ @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 [email protected] Training for your Company: victorrentea.ro
  • 6. 112 © VictorRentea.ro a training by At the beginning There were no functions
  • 7. 113 © VictorRentea.ro a training by At the beginning There were no exceptions
  • 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
  • 10. 116 © VictorRentea.ro a training by Checked Exceptions
  • 11. 117 © VictorRentea.ro a training by code
  • 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
  • 19. 125 © VictorRentea.ro a training by code
  • 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)
  • 24. 131 © VictorRentea.ro a training by The Queen Of All Exceptions
  • 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. 135 © VictorRentea.ro a training by ➔ Useful message in Java 15
  • 28. 136 © VictorRentea.ro a training by NPE How do you fight it ? Throw early Optional
  • 29. 138 © VictorRentea.ro a training by Optional<> For functions that might not return anything
  • 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. 140 © VictorRentea.ro a training by Java 8
  • 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. 143 © VictorRentea.ro a training by code
  • 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: [email protected] For You: victorrentea.teachable.com Questions or Follow: