SlideShare a Scribd company logo
1 of 39
Download to read offline
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/
Victor Rentea
Blog, Talks, Goodies:
VictorRentea.ro
Independent Trainer
Founder of
Bucharest Software Craftsmanship Community
Java Champion
❤️ Simple Design, Refactoring, Unit Testing ❤️
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
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 Runtime
35y, C++: Invisible exceptions
126 © VictorRentea.ro
a training by
We don't Recover
In web apps today, when handling exceptions,This talk is NOT
about library development
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 Exceptions
Shawarma-style
Exception-Handling
+ Runtime bugs= catches all the sh*t
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!
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 ?
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
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);
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
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)
136 © VictorRentea.ro
a training by
code
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
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 the value of some key variable
} catch (AEx e) {
throw new BEx("Info " + id, e);
}
Must-Have
Debugging an Exception
AEx(
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
(rethrow with debug message)
Rethrow as Runtime @SneakyThrows
(Lombok)
for use-case fatal errors
} catch (SomeEx e) {
throw new RuntimeException(e);
}
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 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
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 Optional
for "valid" nulls
149 © VictorRentea.ro
a training by
code
151 © VictorRentea.ro
a training by
Optional<>
Customer.getMemberCard(): Optional<MemberCard>
entity for every nullable column
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.function(CheckedFunction<> f)
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
</dependency>
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>
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/
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

More Related Content

What's hot

Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor Rentea
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityVictor 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
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor 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
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Victor Rentea
 
Clean Code with Java 8 - Functional Patterns and Best Practices
Clean Code with Java 8 - Functional Patterns and Best PracticesClean Code with Java 8 - Functional Patterns and Best Practices
Clean Code with Java 8 - Functional Patterns and Best PracticesVictor 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
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......hugo lu
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional ExplainedVictor Rentea
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT InternalsESUG
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMDierk König
 
FregeFX - JavaFX with Frege, a Haskell for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVMFregeFX - JavaFX with Frege, a Haskell for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVMDierk König
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Dierk König
 
JavaFX - Sketch Board to Production
JavaFX - Sketch Board to ProductionJavaFX - Sketch Board to Production
JavaFX - Sketch Board to ProductionYoav Aharoni
 
Java fx smart code econ
Java fx smart code econJava fx smart code econ
Java fx smart code econTom Schindl
 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks ESUG
 

What's hot (20)

Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
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
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
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
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
 
Clean Code with Java 8 - Functional Patterns and Best Practices
Clean Code with Java 8 - Functional Patterns and Best PracticesClean Code with Java 8 - Functional Patterns and Best Practices
Clean Code with Java 8 - Functional Patterns and Best Practices
 
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
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT Internals
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVM
 
Test
TestTest
Test
 
FregeFX - JavaFX with Frege, a Haskell for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVMFregeFX - JavaFX with Frege, a Haskell for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVM
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015
 
JavaFX - Sketch Board to Production
JavaFX - Sketch Board to ProductionJavaFX - Sketch Board to Production
JavaFX - Sketch Board to Production
 
Java fx smart code econ
Java fx smart code econJava fx smart code econ
Java fx smart code econ
 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
 

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

Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfVictor Rentea
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob Paulin
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java ApplicationVictor 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
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
ruby on rails pitfalls
ruby on rails pitfallsruby on rails pitfalls
ruby on rails pitfallsRobbin Fan
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor Rentea
 
Phone gap android plugins
Phone gap android pluginsPhone gap android plugins
Phone gap android pluginsSimon MacDonald
 
081107 Sammy Eclipse Summit2
081107   Sammy   Eclipse Summit2081107   Sammy   Eclipse Summit2
081107 Sammy Eclipse Summit2mkempka
 
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
 
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
 
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.
 
Building a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdfBuilding a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdfShaiAlmog1
 
Errors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesErrors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesPVS-Studio
 
the grinder testing certification
the grinder testing certificationthe grinder testing certification
the grinder testing certificationVskills
 
Code quality
Code qualityCode quality
Code quality44ue
 

Similar to Definitive Guide to Working With Exceptions in Java - takj at Java Champions Conference (20)

Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
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
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
ruby on rails pitfalls
ruby on rails pitfallsruby on rails pitfalls
ruby on rails pitfalls
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and Java
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Phone gap android plugins
Phone gap android pluginsPhone gap android plugins
Phone gap android plugins
 
081107 Sammy Eclipse Summit2
081107   Sammy   Eclipse Summit2081107   Sammy   Eclipse Summit2
081107 Sammy Eclipse Summit2
 
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
 
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
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
Building a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdfBuilding a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdf
 
Errors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesErrors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 libraries
 
the grinder testing certification
the grinder testing certificationthe grinder testing certification
the grinder testing certification
 
Code quality
Code qualityCode quality
Code quality
 

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
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor 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
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next ChapterVictor Rentea
 

More from Victor Rentea (12)

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
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
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...
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 

Recently uploaded

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
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
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
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
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
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
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
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....
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
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...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 

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

  • 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. 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
  • 6. 123 © VictorRentea.ro a training by At the beginning There were no functions
  • 7. 124 © VictorRentea.ro a training by At the beginning There were no exceptions
  • 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
  • 10. 127 © VictorRentea.ro a training by Checked Exceptions, today
  • 11. 128 © VictorRentea.ro a training by code
  • 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)
  • 19. 136 © VictorRentea.ro a training by code
  • 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); }
  • 25. 142 © VictorRentea.ro a training by The Boss Of All Exceptions
  • 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. 147 © VictorRentea.ro a training by We CHARGE against it! We don't defend against NULL
  • 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. 149 © VictorRentea.ro a training by code
  • 31. 151 © VictorRentea.ro a training by Optional<> Customer.getMemberCard(): Optional<MemberCard> entity for every nullable column
  • 32. 152 © VictorRentea.ro a training by You, defeating the Null Customer.getMemberCard(): Optional<MemberCard>
  • 33. 153 © VictorRentea.ro a training by Java 8
  • 34. 154 © VictorRentea.ro a training by Java 8 Functional Interfaces (eg Function, Predicate, ...) + checked exceptions = pain
  • 35. 155 © VictorRentea.ro a training by code
  • 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