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

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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
 
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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
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
 

Recently uploaded (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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)
 
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...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
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
 

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