The Wayback Machine - https://web.archive.org/web/20180305103642/http://java.sys-con.com:80/node/4148487

Welcome!

Java IoT Authors: Yeshim Deniz, Elizabeth White, Rene Buest, Liz McMillan, Pat Romanski

Related Topics: Java IoT, Containers Expo Blog, @CloudExpo

Java IoT: Article

Mistakes to Avoid When Handling Java Exceptions | @CloudExpo #Java #Cloud #Analytics

You either need to specify or handle a checked exception

Seven Common Mistakes You Should Avoid When Handling Java Exceptions
By Thorben Janssen

Handling an exception is one of the most common but not necessarily one of the easiest tasks. It is still one of the frequently discussed topics in experienced teams, and there are several best practices and common mistakes you should be aware of.

Here are a few things you should avoid when handling exceptions in your application.

Mistake 1: Specify a java.lang.Exception or java.lang.Throwable
As I explained in one of my previous posts, you either need to specify or handle a checked exception. But checked exceptions are not the only ones you can specify. You can use any subclass of java.lang.Throwable in a throws clause. So, instead of specifying the two different exceptions that are thrown by the following code snippet, you could just use the java.lang.Exception in the throws clause.

But that doesn't mean that you should do that. Specifying an Exception or Throwable makes it almost impossible to handle them properly when calling your method.

The only information the caller of your method gets is that something might go wrong. But you don't share any information about the kind of exceptional events that might occur. You're hiding this information behind an unspecific throws clause.

It gets even worse when your application changes over time. The unspecific throws clause hides all changes to the exceptions that a caller has to expect and handle. That might cause several unexpected errors that you need to find by a test case instead of a compiler error.

Use specific classes
It's, therefore, much better to specify the most specific exception classes even if you have to use multiple of them. That tells the caller of your method which exceptional events need to be handled. It also allows you to update the throws clause when your method throws an additional exception. So your clients are aware of the change and even get an error if you change your throws clause. That is much easier to find and handle than an exception that only shows up when you run a particular test case.

Mistake 2: Catch unspecific exceptions
The severity of this mistake depends on the kind of software component you're implementing and where you catch the exception. It might be ok to catch a java.lang.Exception in the main method of your Java SE application. But you should prefer to catch specific exceptions, if you're implementing a library or if you're working on deeper layers of your application.

That provides several benefits. It allows you to handle each exception class differently and it prevents you from catching exceptions you didn't expect.

But keep in mind that the first catch block that handles the exception class or one of its superclasses will catch it. So, make sure to catch the most specific class first. Otherwise, your IDEs will show an error or warning message telling you about an unreachable code block.

Mistake 3: Log and throw an Exception
That is one of the most popular mistakes when handling Java exceptions. It might seem logical to log the exception where it was thrown and then rethrow it to the caller who can implement a use case specific handling. But you should not do it for the following three reasons:

  1. You don't have enough information about the use case the caller of your method wants to implement. The exception might be part of the expected behavior and handled by the client. In this case, there might be no need to log it. That would only add a false error message to your log file which needs to be filtered by your operations team.
  2. The log message doesn't provide any information that isn't already part of the exception itself. Its message and stack trace should provide all relevant information about the exceptional event. The message describes it, and the stack trace contains detailed information about the class, method, and line in which it occurred.
  3. You might log the same exception multiple times when you log it in every catch block that catches it. That messes up the statistics in your monitoring tool and makes the log file harder to read for your operations and development team.

Log it when you handle it
So, better only log the exception when you handle it. Like in the following code snippet. The doSomething method throws the exception. The doMore method just specifies it because the developer doesn't have enough information to handle it. And it then gets handled in the doEvenMore method which also writes a log message.

Mistake 4: Use exceptions to control the flow
Using exceptions to control the flow of your application is considered an anti-pattern for two main reasons:

  1. They basically work like a Go To statement because they cancel the execution of a code block and jump to the first catch block that handles the exception. That makes the code very hard to read.
  2. They are not as efficient as Java's common control structures. As their name indicates, you should only use them for exceptional events, and the JVM doesn't optimize them in the same way as the other code.

So, better use proper conditions to break your loops or if-else-statements to decide which code blocks should be executed.

Mistake 5: Remove original cause of the exception
You sometimes might want to wrap an exception in a different one. Maybe your team decided to use a custom business exception with error codes and a unified handling. There's nothing wrong with this approach as long as you don't remove the cause.

When you instantiate a new exception, you should always set the caught exception as its cause. Otherwise, you lose the message and stack trace that describe the exceptional event that caused your exception. The Exception class and all its subclasses provide several constructor methods which accept the original exception as a parameter and set it as the cause.

Mistake 6: Generalize exceptions
When you generalize an exception, you catch a specific one, like a NumberFormatException, and throw an unspecific java.lang.Exception instead. That is similar to but even worse than the first mistake I described in this post. It not only hides the information about the specific error case on your API, but it also makes it difficult to access.

As you can see in the following code snippet, even if you know which exceptions the method might throw, you can't simply catch them. You need to catch the generic Exception class and then check the type of its cause. This code is not only cumbersome to implement, but it's also hard to read. It get's even worse if you combine this approach with mistake 5. That removes all information about the exceptional event.

So, what's the better approach?

Be specific and keep the cause
That's easy to answer. The exceptions that you throw should always be as specific as possible. And if you wrap an exception, you should also set the original one as the cause so that you don't lose the stack trace and other information that describe the exceptional event.

Mistake 7: Add unnecessary exception transformations
As I explained earlier, it can be useful to wrap exceptions into custom ones as long as you set the original exception as its cause. But some architects overdo it and introduce a custom exception class for each architectural layer. So, they catch an exception in the persistence layer and wrap it into a MyPersistenceException. The business layer catches and wraps it in a MyBusinessException, and this continues until it reaches the API layer or gets handled.

It's easy to see that these additional exception classes don't provide any benefits. They just introduce additional layers that wrap the exception. And while it might be fun to wrap a present in a lot of colorful paper, it's not a good approach in software development.

Make sure to add information
Just think about the code that needs to handle the exception or yourself when you need to find the problem that caused the exception. You first need to dig through several layers of exceptions to find the original cause. And until today, I've never seen an application that used this approach and added useful information with each exception layer. They either generalize the error message and code, or they provide redundant information.

So, be careful with the number of custom exception classes you introduce. You should always ask yourself if the new exception class provides any additional information or other benefits. In most cases, you don't need more than one layer of custom exceptions to achieve that.

More about Java Exceptions
As you've seen, there are several common mistakes you should try to avoid when you handle Java exceptions. That helps you to avoid common bugs and to implement applications that are easy to maintain and to monitor in production.

If this quick list of common mistakes was useful, you should also take a look at my best practices post. It provides you with a list of recommendations that are used by most software development teams to implement their exception handling and to avoid problems like the ones described in this post.

When using Retrace APM with code profiling, you can collect exceptions directly from Java, without any code changes!

The post 7 Common Mistakes You Should Avoid When Handling Java Exceptions appeared first on Stackify.

More Stories By Stackify Blog

Stackify offers the only developers-friendly solution that fully integrates error and log management with application performance monitoring and management. Allowing you to easily isolate issues, identify what needs to be fixed quicker and focus your efforts – Support less, Code more. Stackify provides software developers, operations and support managers with an innovative cloud based solution that gives them DevOps insight and allows them to monitor, detect and resolve application issues before they affect the business to ensure a better end user experience. Start your free trial now stackify.com

@ThingsExpo Stories
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
delaPlex is a global technology and software development solutions and consulting provider, deeply committed to helping companies drive growth, revenue and marketplace value. Since 2008, delaPlex's objective has been to be a trusted advisor to its clients. By redefining the outsourcing industry's business model, the innovative delaPlex Agile Business Framework brings an unmatched alliance of industry experts, across industries and functional skillsets, to clients anywhere around the world.
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
SYS-CON Events announced today that Silicon India has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Published in Silicon Valley, Silicon India magazine is the premiere platform for CIOs to discuss their innovative enterprise solutions and allows IT vendors to learn about new solutions that can help grow their business.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
With privacy often voiced as the primary concern when using cloud based services, SyncriBox was designed to ensure that the software remains completely under the customer's control. Having both the source and destination files remain under the user?s control, there are no privacy or security issues. Since files are synchronized using Syncrify Server, no third party ever sees these files.
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to great conferences, helping you discover new conferences and increase your return on investment.
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
delaPlex is a global technology and software development solutions and consulting provider, deeply committed to helping companies drive growth, revenue and marketplace value. Since 2008, delaPlex's objective has been to be a trusted advisor to its clients. By redefining the outsourcing industry's business model, the innovative delaPlex Agile Business Framework brings an unmatched alliance of industry experts, across industries and functional skillsets, to clients anywhere around the world.
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy high-performance Java applications that use Java 3D and/or Jogl without having to run an installer. We are subject to the constraint that the applications be signed and deployed so that they can be run in a trusted environment (i.e., outside of the sandbox). Further, we seek to do this in a way that does not depend on bundling a JRE with our applications, as this makes downloads and installations rat...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...