如何附加到 Java 异常?
我对 Java 和一般的异常都很陌生。
在我之前的 C/Perl 编程时代,当我编写库函数时,错误会通过布尔标志以及某种带有人类友好(或程序员友好)错误消息的字符串传回。 Java 和 C++ 有异常,这很方便,因为它们包含堆栈跟踪。
我经常发现,当我捕获异常时,我想添加我的两分钱,然后将其传递出去。
这怎么能做到呢?我不想丢弃整个堆栈跟踪......我不知道失败发生的深度以及原因。
我有一个小实用程序库可以将堆栈跟踪(从异常对象)转换为字符串。我想我可以将其附加到我的新异常消息中,但这看起来像是一个黑客。
下面是一个示例方法。建议?
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);
}
}
}
I am new to Java and exceptions in general.
In my prior C/Perl programming days, when I wrote a library function, errors were passed back by a boolean flag, plus some kind of string with a human-friendly (or programmer-friendly) error message. Java and C++ have exceptions, which is handy because they include stack traces.
I often find when I catch an exception, I want to add my two cents, then pass it along.
How can this be done? I don't want to throw away the whole stack trace... I don't know how deep the failure occurred and for what reason.
I have a little utility library to convert a stack track (from an Exception object) into a string. I guess I could append this to my new exception message, but it seems like a hack.
Below is an example method. Advices?
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
异常可以被链接起来:
它使原始异常成为新异常的原因。可以使用 getCause() 获取异常原因,并对新异常调用 printStackTrace() 将会打印:
Exceptions can be chained:
It makes original exception the cause of the new one. Cause of exception can be obtained using
getCause()
, and callingprintStackTrace()
on the new exception will print:通常,您会抛出一个新异常,其中包含旧异常作为“原因”。大多数异常类都有一个接受“原因”异常的构造函数。 (您可以通过 Throwable.getCause() 来实现这一点。)
请注意,您几乎永远不应该只捕获 Exception - 通常您应该捕获更具体类型的异常。
Typically you throw a new exception which includes the old exception as a "cause". Most exception classes have a constructor which accept a "cause" exception. (You can get at this via
Throwable.getCause()
.)Note that you should almost never be catching just
Exception
- generally you should be catching a more specific type of exception.只需使用不同的构造函数:
消息是您的“两分钱”,并且您包含捕获的异常,该异常将显示在堆栈跟踪打印输出中
Just use a different constructor:
The message is your "two cent" and you include the catched exception, which will be shown in a stacktrace printout
您可以将根本原因添加到新创建的异常中:
You can add the underlying cause to a newly created exception: