SlideShare a Scribd company logo
1 of 38
Download to read offline
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

What's hot

Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow oneVictor Rentea
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable ObjectsVictor Rentea
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupVictor Rentea
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor Rentea
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next ChapterVictor Rentea
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Victor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor Rentea
 
Refactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodRefactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodVictor Rentea
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideVictor Rentea
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021Victor Rentea
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional ExplainedVictor Rentea
 
Java fx smart code econ
Java fx smart code econJava fx smart code econ
Java fx smart code econTom Schindl
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT InternalsESUG
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyonddn
 

What's hot (20)

Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable Objects
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 
Refactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodRefactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract Method
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
 
Test
TestTest
Test
 
Java fx smart code econ
Java fx smart code econJava fx smart code econ
Java fx smart code econ
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT Internals
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 

Similar to The Definitive Guide to Working with Exceptions in Java

Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfVictor Rentea
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java ApplicationVictor Rentea
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob Paulin
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Ukraine
 
From Web App Model Design to Production with Wakanda
From Web App Model Design to Production with WakandaFrom Web App Model Design to Production with Wakanda
From Web App Model Design to Production with WakandaAlexandre Morgaut
 
the grinder testing certification
the grinder testing certificationthe grinder testing certification
the grinder testing certificationVskills
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 
Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Wim Godden
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis Engineering Software Lab
 
Phone gap android plugins
Phone gap android pluginsPhone gap android plugins
Phone gap android pluginsSimon MacDonald
 
Debugging in Node.js and Azure
Debugging in Node.js and AzureDebugging in Node.js and Azure
Debugging in Node.js and AzureBrian Clark
 
Scala for Test Automation
Scala for Test AutomationScala for Test Automation
Scala for Test Automationrthanavarapu
 
London SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error HandlingLondon SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error HandlingRichard Clark
 
When Web Services Go Bad
When Web Services Go BadWhen Web Services Go Bad
When Web Services Go BadSteve Loughran
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 

Similar to The Definitive Guide to Working with Exceptions in Java (20)

Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
JavaMicroBenchmarkpptm
JavaMicroBenchmarkpptmJavaMicroBenchmarkpptm
JavaMicroBenchmarkpptm
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
From Web App Model Design to Production with Wakanda
From Web App Model Design to Production with WakandaFrom Web App Model Design to Production with Wakanda
From Web App Model Design to Production with Wakanda
 
Clean Code
Clean CodeClean Code
Clean Code
 
the grinder testing certification
the grinder testing certificationthe grinder testing certification
the grinder testing certification
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
resume_Harikrishnan
resume_Harikrishnanresume_Harikrishnan
resume_Harikrishnan
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
 
Phone gap android plugins
Phone gap android pluginsPhone gap android plugins
Phone gap android plugins
 
Debugging in Node.js and Azure
Debugging in Node.js and AzureDebugging in Node.js and Azure
Debugging in Node.js and Azure
 
Scala for Test Automation
Scala for Test AutomationScala for Test Automation
Scala for Test Automation
 
London SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error HandlingLondon SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error Handling
 
When Web Services Go Bad
When Web Services Go BadWhen Web Services Go Bad
When Web Services Go Bad
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 

More from Victor Rentea

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Victor Rentea
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdfVictor Rentea
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteVictor Rentea
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxVictor Rentea
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxVictor Rentea
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxVictor Rentea
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfVictor Rentea
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Victor Rentea
 

More from Victor Rentea (13)

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdf
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
 

Recently uploaded

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

The Definitive Guide to Working with Exceptions in Java

  • 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. 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
  • 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: victorrentea@gmail.com For You: victorrentea.teachable.com Questions or Follow: