How do I attach to a Java exception?

I am a novice and general exception to Java

In my previous days of C / Perl programming, when I wrote a library function, a boolean flag returned an error, plus a string of human friendly (or programmer friendly) error messages Java and C have exceptions, which is convenient because they include stack traces

I often find that when I catch an exception, I want to add my two cents and pass it on

How can this be done? I don't want to discard the whole stack trace... I don't know the depth and reason of the failure

I have a utility library that converts stack tracks (from exception objects) to strings I think I can attach it to my new exception message, but it seems to be a hacker

The following is an example method Suggestions?

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);
            }
        }
    }

Solution

Exceptions can be linked to:

try {
    ...
} catch (Exception ex) {
    throw new Exception("Something bad happened",ex);
}

It makes the original exception a new cause You can use getcause() to get the cause of the exception and call printstacktrace() to print the new exception:

Something bad happened
... its stacktrace ...
Caused by:
... original exception,its stacktrace and causes ...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>