Java – Top 5 Exception Handling Coding Practices to Avoid
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的更多相关文章
- Exception (3) Java exception handling best practices
List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...
- 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 ...
- JAVA fundamentals of exception handling mechanism
Agenda Three Categories Of Exceptions Exceptions Hierarchy try-catch-finally block The try-with-reso ...
- Java exception handling best practices--转载
原文地址:http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/ This post is anothe ...
- [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 ...
- Exception (2) Java Exception Handling
The Java programming language uses exceptions to handle errors and other exceptional events.An excep ...
- Exception Handling Considered Harmful
异常处理被认为存在缺陷 Do, or do not. There is no try. - Yoda, The Empire Strikes Back (George Lucas) by Jason ...
- [转]java-Three Rules for Effective Exception Handling
主要讲java中处理异常的三个原则: 原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html Exceptions in ...
- 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 ...
随机推荐
- Looksery Cup 2015 F - Yura and Developers 单调栈+启发式合并
F - Yura and Developers 第一次知道单调栈搞出来的区间也能启发式合并... 你把它想想成一个树的形式, 可以发现确实可以启发式合并. #include<bits/stdc+ ...
- Django实战(15):Django实现RESTful web service
曾几何时,Ajax已经统治了Web开发中的客户端,而REST成为web世界中最流行的架构风格(architecture style).所以我们的选择变得很简单:前端ajax访问后端的RESTful w ...
- 002 Jupyter-NoteBook工具介绍(网页版编辑器)
1.Jupyter-NoteBook位置 在安装完anaconda后,这个工具已经被安装完成. 2.打开 3.功能讲解 目录:C:\Users\dell,这个可以看上面控制台上的信息. 4.其余的功能 ...
- Python并发编程系列之协程
1 引言 协程是近几年并发编程的一个热门话题,与Python多进程.多线程相比,协程在很多方面优势明显.本文从协程的定义和意义出发,结合asyncio模块详细讲述协程的使用. 2 协程的意义 2.1 ...
- 【原创】获取MySQL crash 时的core file
最近有台服务器的MySQL经常crash,为了进一步定位问题,开启了mysql core file功能,开启步骤如下,供参考 [开启步骤] 1. my.cnf文件中增加2个配置选项 [mysqld] ...
- (四)静态断言(上),assert,NDEBUG, 以及通过宏定义处理文件包含关系
一.断言:运行时与预处理时 断言(assertion)是一种编程常用的手段.想必大家都见过 assert 吧.今天我们就来了解一下它. 通常情况下,断言就是将一个返回值总是需要为真的判别式放在语句中, ...
- 解决python2.x文件读写编码问题
转自: https://xrlin.github.io/%E8%A7%A3%E5%86%B3python2.x%E6%96%87%E4%BB%B6%E8%AF%BB%E5%86%99%E7%BC%96 ...
- Go Web编程 第四章--处理请求
请求和响应 Request结构 URL字段 Header字段 Body字段 Form, PostForm, MultipartForm字段 在处理器函数中,我们可以通过Request获取各个字段的详细 ...
- python开发_tkinter_获取文本框内容_给文本框添加键盘输入事件
在之前的blog中有提到python的tkinter中的菜单操作 python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐 python开发_tkinter_窗口控件_自 ...
- weblogic安装使用: Could not Create the Java Virtual Machine
第一次使用weblogic,完全不明白是怎么一回事!找安装包花了大把时间!找到了不知道怎么安装 -- _ --||| 找了一篇安装文档<weblogic 安装部署手册.doc>, 位于:[ ...