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

Welcome!

Java IoT Authors: Elizabeth White, Liz McMillan, Pat Romanski, Yeshim Deniz, William Schmarzo

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

Recurring Revenue: Blog Feed Post

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.

Read the original blog entry...

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
SYS-CON Events announced today that WineSOFT will exhibit at 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. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
SYS-CON Events announced today that App2Cloud will exhibit at 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
SYS-CON Events announced today that Akvelon will exhibit at 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. Akvelon is a business and technology consulting firm that specializes in applying cutting-edge technology to problems in fields as diverse as mobile technology, sports technology, finance, and healthcare.
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
SYS-CON Events announced today that Dasher Technologies will exhibit at 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. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we've...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
SYS-CON Events announced today that Massive Networks will exhibit at 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S; Consulting, will present a step-by-step plan to develop your technology implementation strategy. He will discuss the evaluation of communication standards and IoT messaging protocols, dat...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
SYS-CON Events announced today that Datera will exhibit at 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. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can r...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze 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. Launched in 2016, Cloudistics helps anyone bring the power of the cloud to the data center in an easy-to-use, on- premises cloud platform that automatically provides high performance resources for all types of applications: Docke...
SYS-CON Events announced today that CAST Software will exhibit at 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
SYS-CON Events announced today that Golden Gate University will exhibit at 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...