您如何记录未检查的异常? [英] How do you document unchecked exceptions?

查看:103
本文介绍了您如何记录未检查的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

约书亚·布洛赫(Joshua Bloch)在他的《有效的Java》中写道:

Joshua Bloch in his Effective Java writes :

使用Javadoc @throws标记来记录
a方法可能抛出的每个未经检查的异常,但不要使用throws关键字在方法声明中包含未经检查的
异常。

听起来确实合理,但如何查找出来,我的方法可以抛出什么未经检查的异常?

Well that sounds reasonable indeed, but how to find out, what unchecked exception can my method throw?

让我们考虑以下类:

public class FooClass {

    private MyClass[] myClass;

    /**
     * Creates new FooClass
     */
    public FooClass() { 
        // code omitted
        // do something with myClass
    }

    /**
     * Performs foo operation.<br />
     * Whatever is calculated.
     * @param index Index of a desired element
     * @throws HorribleException When something horrible happens during computation
     */
    public void foo(int index) {
        try {
            myClass[index].doComputation();
        } catch (MyComputationException e) {
            System.out.println("Something horrible happened during computation");
            throw new HorribleException(e);
        }
    }
}

现在,我记录了HorribleException,但是很明显,foo方法也可以抛出未经检查的 java.lang.ArrayIndexOutOfBoundsException 。代码变得越复杂,就越难想到该方法可能引发的所有未经检查的异常。我的IDE并没有太大帮助,也没有任何工具。由于我不知道用于此的任何工具...

Now, I documented HorribleException, but it is quite obvious, that foo method can also throw unchecked java.lang.ArrayIndexOutOfBoundsException. The more complex the code gets, it's harder to think of all unchecked exceptions that method can throw. My IDE doesn't help me much there and nor does any tool. Since I don't know any tool for this ...

您如何处理这种情况?

推荐答案

仅记录那些您明确抛出自己或通过其他方法传递的内容。剩余的错误将作为错误,应通过良好的单元测试和编写可靠的代码来修复。

Only document those which you're explicitly throwing yourself or are passing through from another method. The remnant is to be accounted as bugs which are to be fixed by good unit testing and writing solid code.

在这种情况下,我将帐户 ArrayIndexOutOfBoundsException 作为代码中的错误 ,我将相应地修复该代码,使其永远不会抛出该错误。即添加检查数组索引是否在范围内,并通过引发异常(由您记录)或采用替代路径来进行相应处理。

In this particular case, I'd account ArrayIndexOutOfBoundsException as a bug in your code and I'd fix the code accordingly that it never throws it. I.e. add a check if the array index is in range and handle accordingly by either throwing an exception -which you document- or taking an alternative path.

这篇关于您如何记录未检查的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆