This is the material that I prepared for gathering best practices in exception handling that we aim to follow. I used the content stated in the references section.
We like the architecture of our applications to revolve around the business logic, not around technical details (and especially not around the database).
In my team at Sky Network Services we use the Clean Architecture and it has given us a great deal of benefits: the business logic is explicit, we are free to change our technical decisions, the app is easy to test, working on it is faster and scalable, it’s hard to do the wrong thing, and many more.
But it comes at a cost, of course. In this talk I’ll tell you the story of our experience with Clean Architecture and give you some tips to get the most out of it.
Example Project
https://github.com/mattia-battiston/clean-architecture-example
Downloads
Online: https://goo.gl/DTxftJ
PDF: https://goo.gl/ZAtdBN
Powerpoint: https://goo.gl/D54wdZ (but you need to install these fonts to see it properly: https://goo.gl/iH8SO5)
We like the architecture of our applications to revolve around the business logic, not around technical details (and especially not around the database).
In my team at Sky Network Services we use the Clean Architecture and it has given us a great deal of benefits: the business logic is explicit, we are free to change our technical decisions, the app is easy to test, working on it is faster and scalable, it’s hard to do the wrong thing, and many more.
But it comes at a cost, of course. In this talk I’ll tell you the story of our experience with Clean Architecture and give you some tips to get the most out of it.
Example Project
https://github.com/mattia-battiston/clean-architecture-example
Downloads
Online: https://goo.gl/DTxftJ
PDF: https://goo.gl/ZAtdBN
Powerpoint: https://goo.gl/D54wdZ (but you need to install these fonts to see it properly: https://goo.gl/iH8SO5)
This session is all about - the mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
The features released between Java 11 and Java 17 have brought a greater opportunity for developers to improve application development productivity as well and code expressiveness and readability. In this deep-dive session, you will discover all the recent Project Amber features added to the Java language such as Text blocks, Records (including Records serialization), Pattern Matching for instanceof, switch expression, sealed classes, and pattern matching for switch. The main goal of the Amber Project is to bring Pattern Matching to the Java platform, which will impact both the language and the JDK APIs. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
This session is all about - the mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
The features released between Java 11 and Java 17 have brought a greater opportunity for developers to improve application development productivity as well and code expressiveness and readability. In this deep-dive session, you will discover all the recent Project Amber features added to the Java language such as Text blocks, Records (including Records serialization), Pattern Matching for instanceof, switch expression, sealed classes, and pattern matching for switch. The main goal of the Amber Project is to bring Pattern Matching to the Java platform, which will impact both the language and the JDK APIs. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.
Irresponsible Disclosure: Short Handbook of an Ethical DeveloperLemi Orhan Ergin
Ethics... It could be the most important and underrated topic in software industry. It is directly related with professionalism, craftsmanship and professional discipline. From time to time we have to jump into the discussions, however we never discuss it deeper.
I have found himself in a huge blast of discussions when he tweeted about a **HUGE** security issue at the most popular operating system. Then I had deep thoughts about ethics and the behaviours of ethical developers.
In this session I talk about the followings:
* I refer to real-life stories of many good practices for professional ethics that are critical in the software development world.
* I mention technical and non-technical aspects of being an ethical developer.
* I deep dive into the arguments against the ethical controversies and the debate over the sharing of a major error in MacOS via Twitter.
DevOps & Technical Agility: From Theory to PracticeLemi Orhan Ergin
This is the content I presented in meetups for giving brief information about Agile, Devops, Software Craftsmanship, Opertions and Continuous Delivery and their connection with each other.
Yazılım Geliştirme Kültürünün Kodları: Motivasyon, Teknik Mükemmellik ve İnov...Lemi Orhan Ergin
Bugünün acımasız rekabet ortamında hayatta kalabilmek için her şirketin bir yazılım şirketi olması gerekir. Bu çok büyük bir mücadele demek. Kaliteli yazlımcılar işe alınmalı, projeler doğru yönetilmeli ve proje teslim tarihleri belirlenmelidir. Ancak, gerçekte çok farklı bir tabloyla karşılaşıyoruz. Yüzlerce geliştiriciyle iş görüşmesi yapılıyor ancak bulunamıyor. Geliştiricilerden oluşan bir ekip oluşturulsa bile, motivasyonel sorunlar, sürekli artan teknik problemler, iletişim sorunları, inovasyon eksikliği ve işten ayrılmalar ile ediyoruz. Müşteriler, kaçırılan tarihler ve çıktının düşük kalitesi nedeniyle hayal kırıklığına uğruyor.
Her yazılım geliştirme ekibi kendi dinamiklerini yaratır. Çalışanların davranışlarıyla ekiplerin gizli dinamiklerini toplandığımızda şirketteki yazılım geliştirme kültürünü oluşturuyoruz. Bu, bir yazılım geliştirme takımının ne kadar başarılı olabileceğini tanımlayan, en önemli faktörlerden biridir.
Bu oturumda, motivasyon, teknik mükemmellik, işbirliği, yardımlaşma, yenilikçilik ve başarı sağlayan bir yazılım geliştirme kültürünün nasıl kurulacağından bahsedeceğim. Yazılım dünyasına girmiş ve ilgilenen herkes katılabilir.
Bu sunum Dinamikler 2017 Kongresinde kullanılmıştır.
Git Anti-Patterns: How To Mess Up With Git and Love it AgainLemi Orhan Ergin
Git is one of the most powerful tool in developers' toolbox. If you use it correctly, it dramatically increases productivity of developers and eliminates the waste products continuously. Developers cultivate a development culture on top Git most of the time.
It's powerful but its power is untamed. Many teams fall into several traps of misusing commands and therefore feel uncomfortable while using Git. We mess up Git history, the codebase and the whole preferred branching strategy in seconds. We use branches, merge/rebase strategies, creating commits in wrong ways. Even we never take committing paradigms into account while using Git.
As a software craftsman, I've been using Git for years and I've already educated Git to hundreds of developers in all levels. I'm so lucky; I had a chance to experience huge amount of anti-patterns in time. In this talk, I will talk about what those anti-patterns are and what should we do in order not to fall into them.
TDD is the elengant way of designing software. People scares from it so much, because software design is hard and it requires discipline. In this talk, I tried to describe what TDD is from software design perspective.
Karabük Üniversitesi Programlama Günleri 2016'da gerçekleştirdiğim Git sunumu yansılarıdır.
These are the slides of my talk at Karabuk University Programming Days 2016. The slides are in Turkish.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
2. 1
Use Checked Exception for Recoverable error &
Unchecked Exception for programming error
Checked exceptions ensures that you provide exception handling code for error
conditions, which is a way from language to enforcing you for writing robust code,
but same time it also add lots of clutter into code and makes it unreadable. Also,
it seems reasonable to catch exception and do something if you have alternatives
or recovery strategies.
3. 2
Avoid overusing Checked Exception
catch block with multiple exceptions
catch (IOException|SQLException ex) {
logger.log(ex);
}
automatic resource management with try-with-resources
java7
java7
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
Checked Exception has there advantage in terms of enforcement, but at same time
it also litters the code and makes it unreadable by obscuring business logic. You can
minimize this by not overusing checked Exception which result in much cleaner code.
You can also use newer Java 7 features like “one catch block for multiple exceptions”
and “automatic resource management”, to remove some duplication.
4. 3
Converting Checked Exception
into RuntimeException
try {
riskyOperation();
} catch (IOException ioe) {
throw new CustomRuntimeException(ioe);
}
This is one of the technique used to limit use of checked Exception in many of
frameworks like Spring ,where most of checked Exception, which stem from
JDBC is wrapped into DataAccessException, an unchecked Exception. This
Java best practice provides benefits, in terms of restricting specific
exception into specific modules, like SQLException into DAO layer and
throwing meaningful RuntimeException to client layer.
5. 4
Remember Exceptions are costly
in terms of performance
One thing which is worth remembering is that Exceptions are costly, and can
slow down your code. Suppose you have method which is reading from ResultSet
and often throws SQLException than move to next element, will be much slower
than normal code which doesn't throw that Exception. So minimizing catching
unnecessary Exception and moving on, without fixing there root cause. Don’t just
throw and catch exceptions, if you can use boolean variable to indicate result of
operation, which may result in cleaner and performance solution. Avoid
unnecessary Exception handling by fixing root cause.
6. 5
Never swallow the exception in catch block
catch (NoSuchMethodException e) {
return null;
}
Doing this not only return “null” instead of handling or re-throwing the
exception, it totally swallows the exception, losing the cause of error forever.
And when you don’t know the reason of failure, how you would prevent it in
future? Never do this !!
7. 6
Declare the specific checked exceptions
that your method can throw
public void foo() throws Exception {
}
public void foo() throws SpecificException1, SpecificException2 {
}
Always avoid doing this as in above code sample. It simply defeats the whole
purpose of having checked exception. Declare the specific checked
exceptions that your method can throw. If there are just too many such
checked exceptions, you should probably wrap them in your own exception
and add information to in exception message. You can also consider code
refactoring also if possible.
8. 7
Do not catch the Exception class
rather catch specific sub classes
try {
someMethod();
} catch (Exception e) {
LOGGER.error("method has failed", e);
}
The problem with catching Exception is that if the method you are calling later
adds a new checked exception to its method signature, the developer’s intent
is that you should handle the specific new exception. If your code just catches
Exception (or Throwable), you’ll never know about the change and the fact
that your code is now wrong and might break at any point of time in runtime.
9. 8
Never catch Throwable class
try {
someMethod();
} catch (Throwable t) {
// handle throwable
}
Well, its one step more serious trouble. Because java errors are also
subclasses of the Throwable. Errors are irreversible conditions that can not
be handled by JVM itself. And for some JVM implementations, JVM might
not actually even invoke your catch clause on an Error
10. 9
Always correctly wrap the exceptions in custom
exceptions so that stack trace is not lost
catch (NoSuchMethodException e) {
throw new MyServiceException("Some information: " + e.getMessage());
}
catch (NoSuchMethodException e) {
throw new MyServiceException("Some information: " , e);
}
Incorrect way of wrapping exceptions destroys the stack trace of the
original exception, and is always wrong.
11. 10
Either log the exception or throw it
but never do the both
catch (NoSuchMethodException e) {
LOGGER.error("Some information", e);
throw e;
}
Logging and throwing will result in multiple log messages in log files, for a
single problem in the code, and makes life hell for the engineer who is trying
to dig through the logs.
12. 11
Never throw any exception from finally block
try {
// Throws exceptionOne
someMethod();
} finally {
// If finally also threw any exception,
// the exceptionOne will be lost forever
cleanUp();
}
This is fine, as long as cleanUp() can never throw any exception. In the above
example, if someMethod() throws an exception, and in the finally block also,
cleanUp() throws an exception, that second exception will come out of method
and the original first exception (correct reason) will be lost forever. If the code
that you call in a finally block can possibly throw an exception, make sure that
you either handle it, or log it. Never let it come out of the finally block.
13. 12
Always catch only those exceptions
that you can actually handle
catch (NoSuchMethodException e) {
throw e;
}
Well this is most important concept. Don’t catch any exception just for the sake
of catching it. Catch any exception only if you want to handle it or, you want to
provide additional contextual information in that exception. If you can’t handle it
in catch block, then best advice is just don’t catch it only to re-throw it.
14. 13
Don’t use printStackTrace() statement
or similar methods
catch (NoSuchMethodException e) {
System.out.println(e.getStackTrace());
}
Never leave printStackTrace() after finishing your code. Chances are one of
your fellow colleague will get one of those stack traces eventually, and have
exactly zero knowledge as to what to do with it because it will not have any
contextual information appended to it.
15. 14
Use finally blocks instead of catch blocks
if you are not going to handle exception
try {
someMethod();
} finally {
cleanUp(); //do cleanup here
}
This is also a good practice. If inside your method you are accessing
someMethod, and someMethod throws some exception which you do not want
to handle, but still want some cleanup in case exception occur, then do this
cleanup in finally block. Do not use catch block.
16. 15
Remember “Throw early catch late” principle
This is probably the most famous principle about Exception handling. It basically says
that you should throw an exception as soon as you can, and catch it late as much as
possible. You should wait until you have all the information to handle it properly.
!
This principle implicitly says that you will be more likely to throw it in the low-level
methods, where you will be checking if single values are null or not appropriate. And
you will be making the exception climb the stack trace for quite several levels until
you reach a sufficient level of abstraction to be able to handle the problem.
17. 16
Always clean up after handling the exception
If you are using resources like database connections or network
connections, make sure you clean them up. If the API you are invoking
uses only unchecked exceptions, you should still clean up resources
after use, with try – finally blocks. Inside try block access the resource
and inside finally close the resource. Even if any exception occur in
accessing the resource, then also resource will be closed gracefully.
!
You can use new features Java7 to run auto-cleanup via try-withresources statement.
18. 17
Exception names must be
clear and meaningful
Name your checked exceptions stating the cause of the exception. You can
have your own exception hierarchy by extending current Exception class. But for
specific errors, throw an exception like “AccountLockedException” instead of
“AccountException” to be more specific.
19. 18
Throw exceptions for error conditions
while implementing a method
public void someMethod() {
// on error 1
return -‐1;
// on error 2
return -‐2;
}
If you return -1, -2, -3 etc. values instead of FileNotFoundException, that method
can not be understand. Use exceptions on errors.
20. 19
Throw only relevant exception from a method
Relevancy is important to keep application clean. A method which tries to read a file;
if throws NullPointerException, then it will not give any relevant information to user.
Instead it will be better if such exception is wrapped inside custom exception e.g.
NoSuchFileFoundException then it will be more useful for users of that method.
21. 20
Never use exceptions for flow control
Never do that. It makes code hard to read, hard to understand and makes it ugly.
22. 21
Never use exceptions for flow control
in your program
try {
// do some logic
throw new OperationException();
} catch (OperationException e) {
// log the exception message
// or throw a new exception
}
It is useless to catch the exception you throw in the try block. Do not manage
business logic with exceptions. Use conditional statements instead.
23. 22
One try block must exist for
one basic operation
Granularity is very important. One try block must exist for one basic operation. So
don't put hundreds of lines in a try-catch statement.
24. 23
Do not handle exceptions inside loops
for (Message message:messageList) {
try {
// do something that can throw ex.
} catch (SomeException e) {
// handle exception
}
}
try {
for (Message message:messageList) {
// do something that can throw ex.
}
} catch (SomeException e) {
// handle exception
}
Exception handling inside a loop is not recommended for most cases. Surround
the loop with exception block instead.
25. 24
Always include all information
about an exception in single log message
try {
someMethod();
} catch (OperationException e) {
LOGGER.debug(“some message”);
// handle exception
LOGGER.debug(“some another message”);
}
Using a multi-line log message with multiple calls to LOGGER.debug() may look
fine in your test case, but when it shows up in the log file of an app server with
400 threads running in parallel, all dumping information to the same log file,
your two log messages may end up spaced out 1000 lines apart in the log file,
even though they occur on subsequent lines in your code.
26. 25
Pass all relevant information to exceptions
to make them informative as much as possible
catch (SomeException e) {
logger.log(“error occurred”, e);
}
This is also very important to make exception messages and stack traces useful and
informative. What is the use of a log, if you are not able to determine anything out of
it. These type of logs just exist in your code for decoration purpose.
27. 26
Always terminate the thread
which it is interrupted
while (true) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {}
doSomethingCool();
}
while (true) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
break;
}
}
doSomethingCool();
Some common use cases for a thread getting interrupted are the active
transaction timing out, or a thread pool getting shut down. Instead of
ignoring the InterruptedException, your code should do its best to finish up
what it’s doing, and finish the current thread of execution.
28. 27
Use template methods for repeated try-catch
class DBUtil{
public static void closeConnection(Connection conn){
try{
conn.close();
} catch(SQLException ex){
throw new RuntimeException("Cannot close connection", ex);
}
}
}
public void dataAccessCode() {
Connection conn = null;
try{
conn = getConnection();
....
} finally{
DBUtil.closeConnection(conn);
}
}
There is no use of having a similar
catch block in 100 places in your
code. It increases code duplicity
which does not help anything. Use
template methods for such cases.
29. 28
Document all exceptions
in your application in javadoc
Make it a practice to javadoc all exceptions which a piece of code may throw at
runtime. Also try to include possible course of action, user should follow in case
these exception occur.
30. 29
catch all exceptions before
they reach up to the UI
You have to catch all exceptions before they reach up to the UI and
make your user sad. This means on the "highest level" you want to
catch anything that happened further down. Then you can let the user
know there was a problem and at the same time take measures to
inform the developers, like sending out alarm mails or whatever
31. references
Java exception handling best practices
by Lokesh Gupta
http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/
15 Best Practices for Exception Handling
by Cagdas Basaraner
http://codebuild.blogspot.co.uk/2012/01/15-best-practices-about-exception.html
10 Exception handling Best Practices in Java Programming by Javin Paul
http://javarevisited.blogspot.co.uk/2013/03/0-exception-handling-best-practices-in-Java-Programming.html