[转]java的异常处理最佳实践
本文转载自 Karibasappa G C (KB), the Founder of javainsimpleway.com, 原文链接 http://javainsimpleway.com/exception-handling-best-practices/
Exception handling is one of the non-functional requirements for any application development.
We should handle erroneous situations gracefully using exception handling.
Example : Invalid input, File not found in system while reading , number format is not correct etc.
Java provides exception handling to handle these scenarios using try-catch blocks.
There are some set of rules or best practices which we need to follow in exception handling.
Let’s discuss some best practices below
Practice 1
Execute Clean up Resources in a Finally Block or Use a Try-With-Resource Statement
We generally use resource statements like opening a file, or connecting to database etc in the try block and we close it at the end of try block
Example :
- package com.kb.Exception;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- public class ExceptionHandlingCloseResource {
- public static void main(String[] args) {
- FileReader fileReader = null;
- BufferedReader bufferedReader = null;
- try {
- System.out.println("Code to read the data from File");
- fileReader = new FileReader("sample.txt");
- bufferedReader = new BufferedReader(fileReader);
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- System.out.println(line);
- }
- if (bufferedReader != null) {
- bufferedReader.close();
- }
- if (fileReader != null) {
- fileReader.close();
- }
- } catch (IOException e) {
- System.out.println("Inside catch block");
- }
- }
- }
What happens in the above code if there is any exception is thrown in try block ?
Example : While reading file, it may throw FileNotFoundException and thus further lines in try block will not be executed and control goes to catch block.
Because of this, we may end up with not closing the resource which leads to resource leakage.
Its always recommended to write resource closing statements inside finally block as it executes all the time no matter whether exception is thrown or not
- package com.kb.Exception;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- public class ExceptionHandlingCloseResource {
- public static void main(String[] args) {
- FileReader fileReader = null;
- BufferedReader bufferedReader = null;
- try {
- System.out.println("Code to read the data from File");
- fileReader = new FileReader("sample.txt");
- bufferedReader = new BufferedReader(fileReader);
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- System.out.println(line);
- }
- } catch (IOException e) {
- System.out.println("Inside catch block");
- }
- finally {
- if (bufferedReader != null) {
- try {
- bufferedReader.close();
- } catch (IOException e) {
- System.out.println("Log exception while closing bufferedReader");
- }
- }
- if (fileReader != null) {
- try {
- fileReader.close();
- } catch (IOException e) {
- System.out.println("Log exception while closing fileReader");
- }
- }
- }
- }
- }
Practice 2
Never swallow the exception in catch block
- catch (IOException e) {
- return null;
- }
Sometime if our method needs some return value then we handle exception inside catch block and return NULL.
This is dangerous as returning NULL may cause NullPointerException at the caller side and in addition to that we are losing the actual cause of exception
Its better to handle it properly or rethrow the meaningful exception back to caller as below
- catch (IOException e) {
- throw new FileNotFoundException(“File not exist”);
- }
Practice 3
Declare specific exceptions rather than generic exception using throws
- public void readFile() throws Exception {
- }
In the above case, we are wrapping up all the exception into one Exception which does not give much information to caller.
If there are multiple exceptions needs to be thrown then declare each exception separately or create one custom exception and wrap those exceptions in our custom exception and provide meaningful message to caller.
We can do so as below
- public void readFile() throws IOException,SQLException {
- }
Practice 4
Catch most specific exceptions first and then generic exception
This is anyway will not be allowed by java compiler only if we don’t follow this.
We need to write catch blocks for more specific exceptions first as they can be handled first and then generic exception catch block can be written later
- public void catchSpecificExceptionFirst() {
- try {
- readFile("sample.txt");
- } catch (FileNotFoundException e) {
- System.out.println("Log FileNotFoundException while reading file");
- } catch (IOException e) {
- System.out.println("Log IOException while reading file");
- }
- }
In this case, FileNotFoundException is a subclass of IOException and hence that has to be handled first.
Practice 5
Don’t catch Throwable
We know that Throwable is the superclass of all exceptions and errors
We can use Throwable in catch block but we should never do it
Although errors are subclasses of the Throwable, Errors are irreversible conditions that cannot be handled by JVM itself and hence it is not advised to write catch block with Throwable
Practice 6
Correctly wrap the exception details and send it to caller
Its important to wrap the exception details so that exception trace will not be lost
Example : We should not do it like below
- catch (FileNotFoundException e) {
- throw new CustomException("Custom message: " + e.getMessage());
- }
Instead we can do it as below
- catch (FileNotFoundException e) {
- throw new CustomException("Custom message: " ,e);
- }
Practice 7
Don’t log and throw exception instead do one of these 2, but never do both
- catch (FileNotFoundException e) {
- LOGGER.error("Custom message", e);
- throw e;
- }
Logging and throwing the same exception in the same place will result in multiple log messages in log files and makes confusion while analysing the logs
Practice 8
Throw early catch late
This is the most famous principle about Exception handling.
We should throw an exception as soon as we can and we should catch it as late as we can
It means we should throw an exception in low level methods where we execute our business logic and make sure exception is thrown to several layers until we reach specific layer to handle it
Example :
Throw exception in Service layer and handle it in controller in Spring MVC application
Practice 9
Always use single LOG statement to log exception
Example :
- LOGGER.error(“exception occurred “);
- LOGGER.error(e.getMessage());
If we use multiple LOG statements , It makes multiple calls to Logger and also while writing log, this information may not come together as writing to log happens with multi-threading and all threads dump information to same log file which results these lines to spread in different place in log file.
Instead, we can write it using single LOG statement as below
- LOGGER.error(“exception occurred “+e.getMessage());
Practice 10
Avoid empty catch blocks
This is one of the worst coding if you are keeping empty catch block as it hides the exception thrown and there is no handling of that exception, Even if we don’t want to handle it , its better to at least log the exception details in catch block.
Practice 11
Create custom exception only if its necessary
Java has provided lot of exception which can be used in various scenarios
In case, we need to provide additional information then only we should go for custom exception
Practice 12
Document the exceptions using Javadoc
Whenever method throws any exception, its better to document its details using @throw annotation of Javadoc
Clear documentation of Exception thrown by any method provides complete idea of exception to anyone who is using it.
Conclusion
We know that exception handling is very important in software application
development
We should also consider the best practices in handling the exception which
not only increases the readability of program but also provides robust way
of handling the exceptions.
[转]java的异常处理最佳实践的更多相关文章
- Java异常处理最佳实践
总结一些Java异常的处理原则 Java异常处理最佳实践 不要忘记关闭资源 在finally里关闭资源 public void readFile() { FileInputStream fileInp ...
- paip.复制文件 文件操作 api的设计uapi java python php 最佳实践
paip.复制文件 文件操作 api的设计uapi java python php 最佳实践 =====uapi copy() =====java的无,要自己写... ====php copy ...
- Java 网络编程最佳实践(转载)
http://yihongwei.com/2015/09/remoting-practice/ Java 网络编程最佳实践 Sep 10, 2015 | [Java, Network] 1. 通信层 ...
- 避免Java中NullPointerException的Java技巧和最佳实践
Java中的NullPointerException是我们最经常遇到的异常了,那我们到底应该如何在编写代码是防患于未然呢.下面我们就从几个方面来入手,解决这个棘手的问题吧. 值得庆幸的是,通过应用 ...
- 使用DataStax Java驱动程序的最佳实践
引言 如果您想开始建立自己的基于Cassandra的Java程序,欢迎! 也许您已经参加过我们精彩的DataStax Academy课程或开发者大会,又或者仔细阅读过Cassandra Java驱动的 ...
- Java异常处理最佳实践及陷阱防范
前言 不管在我们的工作还是生活中,总会出现各种“错误”,各种突发的“异常”.无论我们做了多少准备,多少测试,这些异常总会在某个时间点出现,如果处理不当或是不及时,往往还会导致其他新的问题出现.所以我们 ...
- SpringBoot系列: Spring项目异常处理最佳实践
===================================自定义异常类===================================稍具规模的项目, 一般都要自定义一组异常类, 这 ...
- java 导出 excel 最佳实践,java 大文件 excel 避免OOM(内存溢出) excel 工具框架
产品需求 产品经理需要导出一个页面的所有的信息到 EXCEL 文件. 需求分析 对于 excel 导出,是一个很常见的需求. 最常见的解决方案就是使用 poi 直接同步导出一个 excel 文件. 客 ...
- java 读取文件最佳实践
1. 前言 Java应用中很常见的一个问题,如何读取jar/war包内和所在路径的配置文件,不同的人根据不同的实践总结出了不同的方案,但其他人应用却会因为环境等的差异发现各种问题,本文则从原理上解释 ...
随机推荐
- LOJ #2537. 「PKUWC 2018」Minimax (线段树合并 优化dp)
题意 小 \(C\) 有一棵 \(n\) 个结点的有根树,根是 \(1\) 号结点,且每个结点最多有两个子结点. 定义结点 \(x\) 的权值为: 1.若 \(x\) 没有子结点,那么它的权值会在输入 ...
- [luogu2446][bzoj2037][SDOI2008]Sue的小球【区间DP】
分析 简单区间DP, 定义状态f[i][j][0/1]为取完i-j的小球最后取i/j上的小球所能获得的最大价值. 排序转移. ac代码 #include <bits/stdc++.h> # ...
- <Android基础>(二) Activity Part 2
1.活动生命周期 1)返回栈 2)活动状态 3)活动的生存期 2.活动的启动模式 1)standard 2)singleTop 3)singleTask 4)singleInstance 3.活动的优 ...
- JQuery未来元素事件监听写法
$(document).on('click','.div1',function(){ alert("abc"); }); 格式一致,第一个参数写事件,第二个参数给谁写事件(选择器) ...
- Django 数据库常见操作
首先要配置数据映射具体在这个连接里 https://www.cnblogs.com/Niuxingyu/p/10296143.html Django 建立数据库模型 #导包导入django数据库类 f ...
- PHP冒泡排序算法
算法说明: 冒泡排序大概的意思是依次比较相邻的两个数,然后根据大小做出排序,直至最后两位数.由于在排序过程中总是小数往前放,大数往后放,相当于气泡往上升,所以称作冒泡排序.但其实在实际过程中也可以根据 ...
- ECharts使用心得总结
https://blog.csdn.net/whiteosk/article/details/52684053 项目中的图表形式很多,基本可以在ECharts中找到相应实例,但UI设计图中的图表跟百度 ...
- 在spring中如何生成一个bean (一个对象,比如jedis的连接池对象)【我】
在spring中,要想生成一个单例对象(比如jedis的连接池对象) 方法1: 在 spring中用 bean 标签生成(反正就是让spring生成并管理单例的对象) 方法2: 把要生成的单例对象类, ...
- 第六节,Neural Networks and Deep Learning 一书小节(下)
4.神经网络可以计算任何函数的可视化证明 神经网络拥有一定的普遍性,即包含一个隐藏层的神经网络可以被用来按照任意给定的精度来近似任何连续函数. 这一章使用一个实例来阐述神经网络是如何来近似一个一元函数 ...
- C sockets Errno
在Windows下进行网络编程,免不了出现各种错误.在Linux下可以使用errno查看错误,但是根据stackoverflow上说,windows下应该使用: FormatMessage() WSA ...