Core Java

10 Best Practices to Handle Java Exceptions

In this article, we will see the best practices to handle Java Exceptions. Exception handling in Java is not an easy matter because novices find it hard to know, and even expert developers can waste hours discussing which Java exceptions should be thrown or handled. Hence maximum development companies have their set of rules on how to use them.

If you are new to a company,  then you might be shocked by how various states present in Java exception handling.  This article will show you ten of the most important ones you can use to get started or improve your exception handling. Exceptions are unusual conditions during a program’s execution. Therefore let’s discuss the best Practices to Handle Java Exceptions.

1. Best Practices to Handle Java Exceptions

1.1 Never consume the exception in a catch block

catch (NoSuchMethodException e) {
   return null;
}

Never do the return “null” rather than handling the exception, it consumes the exception and fails the matter of error permanently. In case you don’t understand the reason behind failure, then you cannot prevent yourself in the future.

1.2 Declare the particular checked exceptions which can be thrown by your method

public void foo() throws Exception { //Incorrect way
}

Always try to avoid the above code because it can create defects in the complete purpose of owning a checked exception. It is necessary to declare the particular checked exceptions which can be thrown by the method. In case a user has many checked exceptions then the user must cover them in the user’s exception and attach information to the exception message or the user can also use code refactoring.

public void foo() throws SpecificException1, SpecificException2 { //Correct way
}

1.3 Don’t get the exception class instead catch particular subclasses

try {
    someMethod();
} 
catch (Exception e) 
{
LOGGER.error("method has failed", e);
}

The major problem with getting an exception is that in case a method the user calls later attaches a newly checked exception to its design signature, the developer intends that a user must handle a particular new exception.  If the user’s code gets an exception, it will never understand the variation. The fact that the user’s code is wrong and it might collapse at a point of time in the runtime.

1.4 Never catch any Throwable class

It is a severe problem because java errors can also be subclasses of a Throwable. Errors are unchangeable conditions which cannot be controlled by the Java virtual machine itself. Java virtual machines might not even request the user’s catch clause on any error.

1.5 Always accurately cover the exceptions in the custom exceptions, so that stack trace is not lost

catch (NoSuchMethodException e) 
{
throw new MyServiceException("Some information: " + e.getMessage());  //Incorrect way
}

The above command can damage the stack trace of the primary exception and is always wrong. The correct way is:

catch (NoSuchMethodException e) {
     throw new MyServiceException("Some information: " , e);  //Correct way
}

1.6 Log the exception or throw it but never do both

catch (NoSuchMethodException e) {
   LOGGER.error("Some information", e);
   throw e;
}

As it is shown in the above code that throwing and logging can result in the multiple log messages in the log files. The single issue in the code can create worst circumstances for the developers who are trying to go through various logs.

1.7 Never throw an exception from finally block

try {
  someMethod();  //Throws exceptionOne
}
 finally 
{
  cleanUp();    //If finally also threw an exception the exceptionOne will be lost forever
}

It is accurate, as high as cleanUp() can nevermore throw an exception. In the above case, if someMethod() throws an exception, and in the ultimately block also, cleanUp() throws an exception, that other exception will grow out of the method and the original first exception (right reason) will be lost forever. 

1.8 Always catch only those exceptions that can be handled

catch (NoSuchMethodException e) 
{
throw e; //Avoid this as it doesn't help anything
}

It is an essential concept never catch any exception so catch any exception only if you can handle it you can give additional contextual data in that exception. If you can’t handle it in the catch block, then the best advice is don’t catch it only to re-throw it.

1.9 Don’t use printStackTrace() statement 

Never leave printStackTrace() after finishing your code. Chances are one of your fellow colleagues who 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.

1.10 Use finally blocks instead of catch blocks if you are not going to handle the exception

try {
  someMethod();  //Method 2
} 
finally 
{
  cleanUp();    //do cleanup here
}

This is also a good practice. If inside your method you are accessing some method 2, and method 2 throws some exception which you do not want to handle in method 1, but still want some cleanup in case an exception occurs, then do this cleanup in the finally block. Do not use the catch block.

As we have discussed that java exception handling is essential and there are various practises to handle them without any issues. The recent VPN app vulnerability that came into the picture is that google removed some best VPN from their platform. According to the researchers, it has dangerous vulnerabilities that support man-in-the-middle (MITM) attacks, so it can simply allow hackers to prevent communications between the provider and the user. Even redirect all users to the hacker’s wicked server rather than a real VPN server. Therefore google removed them to protect the user from vulnerability. Google confirmed that this type of vulnerability still exists and researchers published the conclusion through the Google Play Security Reward Program (GPSRP). GPSRP enables security analysts to uncover vulnerabilities for applications with over 100 million installs.

2. Conclusion

This article helps you to gain complete knowledge regarding the best practices to handle java exceptions. It is essential to have complete knowledge of it because, as we have discussed, this topic is pretty hard for both beginners and experienced developers.

We also discussed the issue between google and top VPN apps that google removed many VPNs from their download platform and provided complete information regarding the issues of VPN apps vulnerability.

Simran Arora

Simran, born in Delhi, did her schooling and graduation from India in Computer Science. Curious and passionate about technology urged her to study for an MS in the same from the renowned Silicon Valley, California USA. Graduated in 2017, she now works as a freelance technical content developer.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
lunchbeast
lunchbeast
3 years ago

Poor grammar, poor English, hard to understand.

Cody
3 years ago

Great help- Thanks.

Back to top button