本文转载自 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 :

  1. package com.kb.Exception;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6.  
  7. public class ExceptionHandlingCloseResource {
  8.  
  9.     public static void main(String[] args) {
  10.         FileReader fileReader = null;
  11.         BufferedReader bufferedReader = null;
  12.         try {
  13.             System.out.println("Code to read the data from File");
  14.             fileReader = new FileReader("sample.txt");
  15.  
  16.             bufferedReader = new BufferedReader(fileReader);
  17.  
  18.             String line;
  19.             while ((line = bufferedReader.readLine()) != null) {
  20.                 System.out.println(line);
  21.             }
  22.  
  23.             if (bufferedReader != null) {
  24.                 bufferedReader.close();
  25.             }
  26.             if (fileReader != null) {
  27.                 fileReader.close();
  28.             }
  29.  
  30.         } catch (IOException e) {
  31.             System.out.println("Inside  catch block");
  32.         }
  33.  
  34.     }
  35.  
  36. }

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

  1. package com.kb.Exception;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6.  
  7. public class ExceptionHandlingCloseResource {
  8.  
  9.     public static void main(String[] args) {
  10.         FileReader fileReader = null;
  11.         BufferedReader bufferedReader = null;
  12.         try {
  13.             System.out.println("Code to read the data from File");
  14.             fileReader = new FileReader("sample.txt");
  15.  
  16.             bufferedReader = new BufferedReader(fileReader);
  17.  
  18.             String line;
  19.             while ((line = bufferedReader.readLine()) != null) {
  20.                 System.out.println(line);
  21.             }
  22.  
  23.         } catch (IOException e) {
  24.             System.out.println("Inside  catch block");
  25.         }
  26.  
  27.         finally {
  28.             if (bufferedReader != null) {
  29.                 try {
  30.                     bufferedReader.close();
  31.                 } catch (IOException e) {
  32.                     System.out.println("Log exception while closing bufferedReader");
  33.                 }
  34.             }
  35.             if (fileReader != null) {
  36.                 try {
  37.                     fileReader.close();
  38.                 } catch (IOException e) {
  39.                     System.out.println("Log exception while closing fileReader");
  40.                 }
  41.             }
  42.         }
  43.  
  44.     }
  45.  
  46. }
Practice 2

Never swallow the exception in catch block

  1. catch (IOException e) {
  2.    return null;
  3. }

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

  1. catch (IOException e) {
  2. throw new FileNotFoundException(“File not exist”);
  3. }
Practice 3

Declare specific exceptions rather than generic exception using throws

  1. public void readFile() throws Exception {
  2. }

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

  1. public void readFile() throws IOException,SQLException {
  2. }
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

  1. public void catchSpecificExceptionFirst() {
  2.     try {
  3.         readFile("sample.txt");
  4.     } catch (FileNotFoundException e) {
  5.         System.out.println("Log FileNotFoundException while reading file");
  6.     } catch (IOException e) {
  7.         System.out.println("Log IOException while reading file");
  8.     }
  9. }

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

  1. catch (FileNotFoundException e) {
  2.    throw new CustomException("Custom message: " + e.getMessage());
  3. }

Instead we can do it as below

  1. catch (FileNotFoundException e) {
  2.    throw new CustomException("Custom message: " ,e);
  3. }
Practice 7

Don’t log and throw exception instead do one of these 2, but never do both

  1. catch (FileNotFoundException e) {
  2.    LOGGER.error("Custom message", e);
  3.    throw e;
  4. }

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 :

  1. LOGGER.error(“exception occurred “);
  2. 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

  1. 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的异常处理最佳实践的更多相关文章

  1. Java异常处理最佳实践

    总结一些Java异常的处理原则 Java异常处理最佳实践 不要忘记关闭资源 在finally里关闭资源 public void readFile() { FileInputStream fileInp ...

  2. paip.复制文件 文件操作 api的设计uapi java python php 最佳实践

    paip.复制文件 文件操作 api的设计uapi java python php 最佳实践 =====uapi   copy() =====java的无,要自己写... ====php   copy ...

  3. Java 网络编程最佳实践(转载)

    http://yihongwei.com/2015/09/remoting-practice/ Java 网络编程最佳实践 Sep 10, 2015 | [Java, Network] 1. 通信层 ...

  4. 避免Java中NullPointerException的Java技巧和最佳实践

    Java中的NullPointerException是我们最经常遇到的异常了,那我们到底应该如何在编写代码是防患于未然呢.下面我们就从几个方面来入手,解决这个棘手的​问题吧.​ 值得庆幸的是,通过应用 ...

  5. 使用DataStax Java驱动程序的最佳实践

    引言 如果您想开始建立自己的基于Cassandra的Java程序,欢迎! 也许您已经参加过我们精彩的DataStax Academy课程或开发者大会,又或者仔细阅读过Cassandra Java驱动的 ...

  6. Java异常处理最佳实践及陷阱防范

    前言 不管在我们的工作还是生活中,总会出现各种“错误”,各种突发的“异常”.无论我们做了多少准备,多少测试,这些异常总会在某个时间点出现,如果处理不当或是不及时,往往还会导致其他新的问题出现.所以我们 ...

  7. SpringBoot系列: Spring项目异常处理最佳实践

    ===================================自定义异常类===================================稍具规模的项目, 一般都要自定义一组异常类, 这 ...

  8. java 导出 excel 最佳实践,java 大文件 excel 避免OOM(内存溢出) excel 工具框架

    产品需求 产品经理需要导出一个页面的所有的信息到 EXCEL 文件. 需求分析 对于 excel 导出,是一个很常见的需求. 最常见的解决方案就是使用 poi 直接同步导出一个 excel 文件. 客 ...

  9. java 读取文件最佳实践

    1.  前言 Java应用中很常见的一个问题,如何读取jar/war包内和所在路径的配置文件,不同的人根据不同的实践总结出了不同的方案,但其他人应用却会因为环境等的差异发现各种问题,本文则从原理上解释 ...

随机推荐

  1. 数论细节梳理&模板

    初阶 扩展欧拉 \(k\ge\varphi(m)\)时,\(b^k\equiv b^{k\%\varphi(m)+\varphi(m)}(\bmod m\)) 扩展CRT 推式子合并同余方程. htt ...

  2. 自学zabbix集锦

    zabbix概念集锦 01 Zabbix采集数据方式 02 开源监控软件Cacti.nagios 03 Zabbix常用的术语 04 Zabbix核心概念回顾 05 Zabbix triggers-- ...

  3. 自学华为IoT物联网_02 常见物联网通信技术

    点击返回自学华为IoT物流网 自学华为IoT物联网_02 常见物联网通信技术 两类技术: 有线通信技术 无线通信技术 一. 有线通信技术 1.1 物联网有线技术介绍及对比 ETH 主要用于支持以太网标 ...

  4. 搭建本地yum源并定时同步

    在生产中内网的机器都是不能访问外网,所以需要搭建本地yum源.以中国科学科技大学的yum源为基准.http://mirrors.ustc.edu.cn/ 有些模块会同步失败,可以wget下载至指定位置 ...

  5. 【dfs】p1451 求细胞数量

    题目描述 一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右若还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数.(1<=m,n<=100)? 输入输出格式## ...

  6. luogu1919 A*BProblem升级版 (FFT)

    把一个n位数看做n-1次的多项式,每一项的系数是反过来的每一位最后每一项系数进进位搞一搞就行了(数组一定要开到2的次数..要不然极端数据会RE) #include<cstdio> #inc ...

  7. 蓝桥杯试题 k倍区间(dp)

    问题描述 给定一个长度为N的数列,A1, A2, ... AN,如果其中一段连续的子序列Ai, Ai+1, ... Aj(i <= j)之和是K的倍数,我们就称这个区间[i, j]是K倍区间. ...

  8. webpack入门(二)what is webpack

    webpack is a module bundler.webpack是一个模块打包工具,为了解决上篇一提到的各种模块加载或者转换的问题. webpack takes modules with dep ...

  9. 基于Jenkins,docker实现自动化部署(持续交互)

      前言 随着业务的增长,需求也开始增多,每个需求的大小,开发周期,发布时间都不一致.基于微服务的系统架构,功能的叠加,对应的服务的数量也在增加,大小功能的快速迭代,更加要求部署的快速化,智能化.因此 ...

  10. 【CF1141F1】Same Sum Blocks

    题目大意:给定一个 N 个值组成的序列,求序列中区间和相同的不相交区间段数量的最大值. 题解:设 \(dp[i][j]\) 表示到区间 [i,j] 时,与区间 [i,j] 的区间和相同的不相交区间数量 ...