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);
}
}
}
Exceptions can be chained:
try {
...
} catch (Exception ex) {
throw new Exception("Something bad happened", ex);
}
It makes original exception the cause of the new one. Cause of exception can be obtained using getCause()
, and calling printStackTrace()
on the new exception will print:
Something bad happened ... its stacktrace ... Caused by: ... original exception, its stacktrace and causes ...
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:
Exception(String message, Throwable cause)
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:
throw new Exception("Failed to process input ["
+ ((null == input) ? "null" : input)
+ "] at index " + i + ": " + Arrays.toString(input_array)
+ "\n" + e.getMessage(), e);
精彩评论