1. Overview

In this article, we’ll have a very brief look at what Exception is and go in depth about discussing the chained exceptions in Java.

Simply put, an exception is an event that disturbs the normal flow of the program’s execution. Let’s now see exactly how we can chain exceptions to get better semantics out of them.

2. Chained Exceptions

Chained Exception helps to identify a situation in which one exception causes another Exception in an application.

For instance, consider a method which throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero.The method will throw the ArithmeticException to the caller. The caller would not know about the actual cause of an Exception. Chained Exception is used in such situations.

This concept was introduced in JDK 1.4.

Let’s see how chained exceptions are supported in Java.

3. Throwable Class

Throwable class has some constructors and methods to support chained exceptions. Firstly, let’s look at the constructors.

  • Throwable(Throwable cause) – Throwable has a single parameter, which specifies the actual cause of an Exception.
  • Throwable(String desc, Throwable cause) – this constructor accepts an Exception description with the actual cause of an Exception as well.

Next, let’s have a look at the methods this class provides:

  • getCause() method – This method returns the actual cause associated with current Exception.
  • initCause() method – It sets an underlying cause with invoking Exception.

4. Example

Now, let’s look at the example where we will set our own Exception description and throw a chained Exception:

1
2
3
4
5
6
7
8
9
10
11
12
public class MyChainedException {
    public void main(String[] args) {
        try {
            throw new ArithmeticException("Top Level Exception.")
              .initCause(new IOException("IO cause."));
        } catch(ArithmeticException ae) {
            System.out.println("Caught : " + ae);
            System.out.println("Actual cause: "+ ae.getCause());
        }
    }   
}

As guessed, this will lead to:

1
2
Caught: java.lang.ArithmeticException: Top Level Exception.
Actual cause: java.io.IOException: IO cause.

5. Why Chained Exceptions?

We need to chain the exceptions to make logs readable. Let’s write two examples. First without chaining the exceptions and second, with chained exceptions. Later, we will compare how logs behave in both of the cases.

To start, we will create a series of Exceptions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class NoLeaveGrantedException extends Exception {
    public NoLeaveGrantedException(String message, Throwable cause) {
        super(message, cause);
    }
    public NoLeaveGrantedException(String message) {
        super(message);
    }
}
class TeamLeadUpsetException extends Exception {
    // Both Constructors
}

Now, let’s start using the above exceptions in code examples.

5.1. Without Chaining

Let’s write an example program without chaining our custom exceptions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MainClass {
    public void main(String[] args) throws Exception {
        getLeave();
    }
    void getLeave() throws NoLeaveGrantedException {
        try {
            howIsTeamLead();
        } catch (TeamLeadUpsetException e) {
            e.printStackTrace();
            throw new NoLeaveGrantedException("Leave not sanctioned.");
        }
    }
    void howIsTeamLead() throws TeamLeadUpsetException {
        throw new TeamLeadUpsetException("Team Lead Upset");
    }
}

In the example above, logs will look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
com.baeldung.chainedexception.exceptions.TeamLeadUpsetException:
  Team lead Upset
    at com.baeldung.chainedexception.exceptions.MainClass
      .howIsTeamLead(MainClass.java:46)
    at com.baeldung.chainedexception.exceptions.MainClass
      .getLeave(MainClass.java:34)
    at com.baeldung.chainedexception.exceptions.MainClass
      .main(MainClass.java:29)
Exception in thread "main" com.baeldung.chainedexception.exceptions.
  NoLeaveGrantedException: Leave not sanctioned.
    at com.baeldung.chainedexception.exceptions.MainClass
      .getLeave(MainClass.java:37)
    at com.baeldung.chainedexception.exceptions.MainClass
      .main(MainClass.java:29)

5.2. With Chaining

Next, let’s write an example with chaining our custom exceptions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MainClass {
    public void main(String[] args) throws Exception {
        getLeave();
    }
    public getLeave() throws NoLeaveGrantedException {
        try {
            howIsTeamLead();
        } catch (TeamLeadUpsetException e) {
             throw new NoLeaveGrantedException("Leave not sanctioned.", e);
        }
    }
    public void howIsTeamLead() throws TeamLeadUpsetException {
        throw new TeamLeadUpsetException("Team lead Upset.");
    }
}

Finally, let’s look at the logs obtained with chained exceptions:

1
2
3
4
5
6
7
8
9
10
11
12
13
Exception in thread "main" com.baeldung.chainedexception.exceptions
  .NoLeaveGrantedException: Leave not sanctioned.
    at com.baeldung.chainedexception.exceptions.MainClass
      .getLeave(MainClass.java:36)
    at com.baeldung.chainedexception.exceptions.MainClass
      .main(MainClass.java:29)
Caused by: com.baeldung.chainedexception.exceptions
  .TeamLeadUpsetException: Team lead Upset.
    at com.baeldung.chainedexception.exceptions.MainClass
  .howIsTeamLead(MainClass.java:44)
    at com.baeldung.chainedexception.exceptions.MainClass
  .getLeave(MainClass.java:34)
    ... 1 more

We can easily compare shown logs and conclude that the chained exceptions lead to cleaner logs.

6. Conclusion

In this article, we had a look at chained exceptions concept.

The implementation of all examples can be found in the Github project – this is a Maven-based project, so it should be easy to import and run as it is.

转载于:https://www.cnblogs.com/sidesky/p/10621600.html

Chained Exceptions in Java相关推荐

  1. 【已解决】Exception in thread “Thread-0“ redis.clients.jedis.exceptions.JedisConnectionException: java.n

    问题: Exception in thread "Thread-0" redis.clients.jedis.exceptions.JedisConnectionException ...

  2. Exceptions In Java

    Java中的异常分为两种类型:checked Exception和unchecked Exception. Why did the designers decide to force a method ...

  3. redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refu

            今天在做Redis 测试的时候遇到一个错误,写一篇博客博客记录一下:          错误: redis.clients.jedis.exceptions.JedisConnecti ...

  4. redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refus

    今天在连接redis时出现了一个奇怪的错误.如下: public class RedisTest {@Testpublic void redisTest(){// 连接RedisJedis jedis ...

  5. com.baomidou.mybatisplus.core.exceptions.MyBatisPlusException: java.net.UnknownHostException

    这个问题,后面跟的是服务器的hostname, name not resolve 是因为无法解析服务器的hostname导致的报错,服务器上vim /etc/hosts增加hostname解析之后,重 ...

  6. arm32 linux 内存分布,gcc代码反汇编查看内存分布[2]: arm-linux-gcc

    arm-none-linux-gnueabi-gcc -v gcc version 4.4.1 (Sourcery G++ Lite 2010q1-202) 重点: 代码中的内存分配, 地址从低到高: ...

  7. java.lang.NoClassDefFoundError: org/apache/hadoop/yarn/exceptions/YarnException

    flink提交任务卡死,cancel job以后,在$FLINK_HOME/log/flink-appleyuchi-client-Desktop.log 发现该报错: java.lang.NoCla ...

  8. java多层catch语句_Java异常之catch语句块

    今天在阅读项目代码时看到如下奇怪的代码,以为是竖线 | 可以作为多类型赋值,经过网上搜索才知道是Java SE 7新增的功能:一个catch捕获多种类型的异常.原文是Java官方的文档,现翻译如下.红 ...

  9. Java编程思想 (1~10)

    [注:此博客旨在从<Java编程思想>这本书的目录结构上来检验自己的Java基础知识,只为笔记之用] 第一章 对象导论 1.万物皆对象 2.程序就是对象的集合 3.每个对象都是由其它对象所 ...

最新文章

  1. java 基础知识三 java变量
  2. linux 新增swap分区
  3. phpmyadmin底部出现提示“The configuration file now needs a secret passphrase (blowfish_secret). ”...
  4. linux下lua bit模块的安装
  5. Codeforces937D Sleepy Game
  6. [js] script所在的位置会影响首屏显示时间吗
  7. 它有许多功能的局域网
  8. 如何从网站提取数据?
  9. 学UI设计要学哪些软件
  10. 中心极限与大数定理律的关系_21厦大数学考研 | 数列与函数极限复习建议!
  11. 慎用!闲鱼APP竟然成为了诈骗犯的庇护所!
  12. 毛刺现象 java_硬件毛刺
  13. 周易六十四卦——泽水困卦
  14. cad考试题库绘图题答案_最新CAD考试题库及答案-cad考试题库绘图题答案
  15. 分析游戏外挂样本的9大诀窍
  16. webstorm 扩大内存
  17. 失去优秀员工会付出惨痛的代价?
  18. 交互技术前沿学习分享-翻译
  19. c1灯光语言,c1科目三路考灯光口诀
  20. web开发与django认识 MVC和MVT的区别 路由的匹配

热门文章

  1. R_circlize包_和弦图(二)
  2. 30条人生经验分享~(摘录)
  3. mathematica中画图技巧
  4. HTML5中国象棋游戏(自定义象棋难度)源码下载
  5. web移动端开发-将网站分享朋友圈、微信空间、朋友圈功能
  6. 基于Aidlux平台的智慧交通AI安全算法实战
  7. Android特效专辑(一)——水波纹过渡特效(首页)
  8. MySQL数据库中时间戳及时间戳的格式转换
  9. 文本分类半监督学习--UDA
  10. 51nod 1475:建设国家 优先队列的好题