Introduction to Guava Throwables – 番石榴可抛物简介

最后修改: 2020年 4月 6日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’re going to take a quick look at Google Guava’s Throwables class.

在这篇文章中,我们将快速浏览一下Google Guava的Throwables类。

This class contains a set of static utility methods for dealing with exception handling and:

该类包含一组静态的实用方法,用于处理异常处理和。

  • propagation
  • processing the cause chain

2. Maven Dependency

2.Maven的依赖性

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

3. Propagation

3.传播

Let’s assume we interact with some code that throws a generic Throwable.

让我们假设我们与一些抛出通用Throwable的代码交互。

In most cases, we want to convert this to a RuntimeException if it’s a direct subclass of Throwable.

在大多数情况下,如果它是Throwable的直接子类,我们希望将其转换为RuntimeException

However, if it’s an instance of Error, RuntimeException or Exception we can invoke the propagateIfPossible to propagate it as-is:

然而,如果它是Error、RuntimeExceptionException的实例,我们可以调用propagateIfPossible来按原样传播它。

try {
    methodThatMightThrowThrowable();
} catch (Throwable t) {
    Throwables.propagateIfPossible(t, Exception.class);
    throw new RuntimeException(t);
}

4. Causal Chain

4.因果链

Guava also provides utility methods for inspecting the thrown exception and its chain.

Guava还提供了检查抛出的异常及其链的实用方法。

Throwable getRootCause(Throwable)

The getRootCause method allows us to get the innermost exception, which is useful when we want to find the initial cause.

getRootCause方法允许我们获得最内部的异常,这在我们想找到最初的原因时很有用。

List<Throwable> getCausalChain(Throwable)

This getCausalChain method will return a list of all the throwables in the hierarchy. This is handy if we want to check if it contains a certain type of exception.

这个getCausalChain方法将返回一个层次结构中所有可抛物的列表。如果我们想检查它是否包含某种类型的异常,这很方便

String getStackTraceAsString(Throwable)

The getStackTraceAsString method will return the recursive stack trace of the exception.

getStackTraceAsString方法将返回异常的递归堆栈跟踪。

5. Conclusion

5.总结

In this tutorial, we illustrated some examples where we can use Guava’s Throwables class to simplify dealing with exceptions.

在本教程中,我们说明了一些例子,我们可以使用Guava的Throwables类来简化异常的处理。

As always, the complete source code is available over on GitHub.

一如既往,完整的源代码可在GitHub上获得