如何附加Java异常?

kev*_*rpe 11 java exception stack-trace

我是Java的新手和一般的例外.

在我之前的C/Perl编程时,当我编写库函数时,错误被布尔标志传回,加上某种带有人性化(或程序员友好)错误消息的字符串.Java和C++有异常,这很方便,因为它们包含堆栈跟踪.

我经常发现当我遇到异常时,我想加上我的两分钱,然后传递它.

如何才能做到这一点?我不想丢掉整个堆栈跟踪......我不知道故障发生的深度和原因.

我有一个小工具库来将堆栈轨道(从Exception对象)转换为字符串.我想我可以将此附加到我的新异常消息,但它似乎是一个黑客.

以下是一个示例方法.建议?


    public void foo(String[] input_array) {
        for (int i = 0; i < input_array.length; ++i) {
            String input = input_array[i];
            try {
                bar(input);
            }
            catch (Exception e) {
                throw new Exception("Failed to process input [" 
                        + ((null == input) ? "null" : input)
                        + "] at index " + i + ": " + Arrays.toString(input_array) 
                        + "\n" + e);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 27

可以链接例外情况:

try {
    ...
} catch (Exception ex) {
    throw new Exception("Something bad happened", ex);
}
Run Code Online (Sandbox Code Playgroud)

它使原始异常成为新原因的原因.可以使用获取异常的原因getCause(),并调用printStackTrace()新的异常将打印:

Something bad happened
... its stacktrace ...
Caused by:
... original exception, its stacktrace and causes ...