This article represents top 5 coding practices related with Java exception handling that you may want to watch out for or better say, avoid, while doing coding for exception handling. Recently, I have been involved with code review of multiple Java projects and found following as most commonly seen coding instances across various Java projects. As a matter of fact, I recently ran sonar code analysis on Spring Core project (Spring Framework) and found the below mentioned instances related with exception handling. Please note that these are suggested to be avoided as a general coding practice and do not mean that they can not be used at all. There are still cases where one may end up using coding practice against following, but that should happen on case-to-case basis and not as a general practice. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.

Throwable and Error classes should not be caught

One should try and avoid catching Throwable and Errors in their code. There is a very detailed article written on this topic on this page. Following is an example of non-compliant code taken from Spring-core code:

try {
cl = Thread.currentThread().getContextClassLoader();
}catch (Throwable ex) { //Non-compliant code
}

In nutshell, following are some of the reasons:

  • Throwable is the superclass of all errors and exceptions in Java. Error is the superclass of all errors which are not meant to be caught by applications. Thus, catching Throwable would essentially mean that Errors such as system exceptions (e.g., OutOfMemoryError, StackOverFlowError or InternalError) would also get caught. And, the recommended approach is that application should not try and recover from Errors such as these. Thus, Throwable and Error classes should not be caught. Only Exception and its subclasses should be caught.

Above said, there are reasons why people still go for catching Throwable. The data errors such as encoding issues etc which are not known at programming time can be caught using this technique. However, catching Throwable such as InternelError or OutofMemoryError would not be of any help and should therefore be thrown. Thus, one should avoid writing code consisting of catching Throwable as general practice.

Throwable.printStackTrace(…) should never be called

Following is an example of code that represents the usage of invocation of printStackTrace on Throwable class.

try {
/* ... */
} catch(Throwable e) {
e.printStackTrace(); // Non-Compliant
}

Following are some of the reasons why one should avoid invoking printStackTrace method on Throwable/Exception classes and instead use Logger method using one of the frameworks such as LogBack or Log4J:

  • Difficult to Retrieve Logs for Debugging:The logs written using printStackTrace is written to System.err which is hard to route or filter elsewhere. Instead, using Loggers, it is easy to retrieve logs for debugging purpose.
  • Violation of Coding Best Practices:Generally, as per coding guidelines in production-ready applications, developers need to use Logger methods for logging different level of information. However, when it comes to exception handling, the instances of printStackTrace are commonly found in various places. This is, thus, a violation of coding practice and, thus, should be avoided.
  • Following are some good pages explaining the reasons in detail:

Generic exceptions such as Error, RuntimeException, Throwable and Exception should never be thrown

Following are some of the reasons why Generic Exceptions/Throwable should never be thrown:

  • The primary reason why one should avoid throwing Generic Exceptions, Throwable, Error etc is that doing in this way prevents classes from catching the intended exceptions. Thus, a caller cannot examine the exception to determine why it was thrown and consequently cannot attempt recovery.
  • Additionally, catching RuntimeException is considered as a bad practice. And, thus, throwing Generic Exceptions/Throwable would lead the developer to catch the exception at a later stage which would eventually lead to further code smells.

Following is the code sample that represents this code smell:

public void foo(String bar) throws Throwable { // Non-compliant
throw new RuntimeException("My Message"); // Non-Compliant
}
// One other instance which displays throwing Exception
public void doSomething() throws Exception {...} // Non-compliant code

Instead, one would want to do something like following:

public void foo(String bar) {
throw new CustomRuntimeException("My Message"); // Compliant
}

Exception handlers should preserve the original exception

When writing code for doing exception handling, I have often seen code such as following which does some of the following:

In the code sample below, the exception is lost.

try {
/* ... */
} catch( Exception e ) {
// The exception is lost. Just that exception message is written; Also, context information is not logged.
SomeLogger.info( e.getMessage() );
}

In the code sample below, whole exception object is lost.

try {
/* ... */
} catch( Exception e ) {
SomeLogger.info( "some context message" ); // The exception is lost
}

In the code sample below, no context message is provided.

try {
/* ... */
} catch( Exception e ) {
SomeLogger.info( e ); // No context message
}

As a best practice, one would want to do something like following:

try {
/* ... */
} catch( Exception e ) {
// Context message is there. Also, exception object is present
SomeLogger.info( "some context message", e );
}

In case of throwable exceptions, following should be done:

try {
/* ... */
} catch (Exception e) {
// Context message is there. Also, exception object is present
throw new CustomRuntimeException("context", e);
}

System.out or System.err should not be used to log exceptions

The primary reason why one should avoid using System.out or System.err to log exception is the fact that one might simply loose the important error messages. Instead one should use Logging frameworks such as Log4J or LogBack etc to log the exceptions.

Java – Top 5 Exception Handling Coding Practices to Avoid的更多相关文章

  1. Exception (3) Java exception handling best practices

    List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...

  2. Java – 4 Security Vulnerabilities Related Coding Practices to Avoid---reference

    This article represents top 4 security vulnerabilities related coding practice to avoid while you ar ...

  3. JAVA fundamentals of exception handling mechanism

    Agenda Three Categories Of Exceptions Exceptions Hierarchy try-catch-finally block The try-with-reso ...

  4. Java exception handling best practices--转载

    原文地址:http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/ This post is anothe ...

  5. [fw]Best Practices for Exception Handling

    http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html http://www.onjava.com/pub/a/onjava/200 ...

  6. Exception (2) Java Exception Handling

    The Java programming language uses exceptions to handle errors and other exceptional events.An excep ...

  7. Exception Handling Considered Harmful

    异常处理被认为存在缺陷 Do, or do not. There is no try. - Yoda, The Empire Strikes Back (George Lucas) by Jason ...

  8. [转]java-Three Rules for Effective Exception Handling

    主要讲java中处理异常的三个原则: 原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html Exceptions in ...

  9. Java Tips and Best practices to avoid NullPointerException

    A NullPointerException in Java application is best way to solve it and that is also key to write rob ...

随机推荐

  1. HDU - 4420 2013icpc长春A 函数离散化 + st表

    思路:我们定义F(x) 为以x点为起点,向后(a - b)个里面有多少个白球,虽然x的范围是LL范围内的,但是白球的 个数只有1e5, 那么我们可以把连续一段相同的离散化到一起, 对于一个确定的长度为 ...

  2. 纯CSS仿制Google女生节Doodle

    看到google今天的女生节Doodle,自己用纯css仿制一个,送给老妈.老婆.女儿. 大家可以点这里在线观看效果,点这里下载收藏效果. 实现原理 1.利用checkbox侦听处理单击事件. 2.单 ...

  3. jQuery 的运行机制(How jQuery Works)

    原文地址:http://learn.jquery.com/about-jquery/how-jquery-works/ linkjQuery: 基础知识 这是一个基本的教程,旨在帮助您开始使用jQue ...

  4. 构建第一个Spring Boot项目

    1.启动IntelliJ IDEA,点击"Create New Project"  2.选择"Spring initializr",设定SDK及Spring ...

  5. PHP老师没教过你的那些知识点

    另类的写法有惊喜 我们在阅读某些源代码的时候会发现有一种另类的写法,比如 //异常写法 if(false == $result)   //正常写法 if($result == false) 其实这是一 ...

  6. java_String、StringBuilder

    在介绍String和StringBuilder前先学习一下equals方法和toString方法.API java1.6提取码:04b6 equals方法 equals方法,用于比较两个对象是否相同, ...

  7. 【*】Redis常见问题汇总

    1.什么是Redis? Redis是一个开源.高性能.基于键值对的缓存与存储系统. 2.Redis相比memcached有哪些优势? 劣势:Redis是单线程,Memcached是多线程,在多核服务器 ...

  8. Python并发编程系列之多进程(multiprocessing)

    1 引言 本篇博文主要对Python中并发编程中的多进程相关内容展开详细介绍,Python进程主要在multiprocessing模块中,本博文以multiprocessing种Process类为中心 ...

  9. SQLSERVER2014集群实战——IP引发的坑

    在之前的帖子里有提到过,为了避免IP变更带来的一系列问题,采取了不改变IP的策略.原以为,只要SQLSERVER的群集IP保持与之前单机部署的IP一致,就基本上不会有问题.然而实际永远比预想的更复杂. ...

  10. CodeForces 1070J Streets and Avenues in Berhattan 性质+动态规划

    题目大意: 你有$k$个数,分为$26$种 对于每个数,你可以选择选进$A$集合或者$B$集合或者不选 要求$A$集合中必须有$n$个数,$B$集合中必须有$m$个数 记第$i$种数在$A$集合中的个 ...