Reputation: 459
The dangerousMethodHandler() prints the stack trace of the error from a StackTraceElement array when an illegal argument exception is caught. For any other types of exceptions, the dangerousMethodHandler() prints "Exception!"
I currently have sorted out the other exception but can't seem to implement my code using the StackTraceElemen array
public void dangerousMethod() {
Character.toChars(~0);
}
public void dangerousMethodHandler() {
try {
this.dangerousMethod();
}catch(IllegalArgumentException e){
StackTraceElement[] trace = e.getStackTrace();
e.getStackTrace();
System.err.println(trace[0].toString());
} catch (Exception e){
System.out.print("Exception!");
}
}
When I print out the following I get
java.lang.Character.toChars(Character.java:4982)
My output should be :
java\.lang\.Character\.toChars\(Character\.java:\d+\)[\s\n]+Main\.dangerousMethod\(Main\.java:\d+\)[\s\n]+Main\.dangerousMethodHandler\(Main\.java:\d+\)[\s\n]+Main\.runTests\(Main\.java:\d+\)[\s\n]+Main\.main\(Main\.java:\d+\)
Upvotes: 3
Views: 9200
Reputation: 709
Try to do below:
Arrays.stream(e.getStackTrace()).skip(0).map(StackTraceElement::toString).reduce((s1, s2) -> s1 + "\n" + s2).get()
In reduce you can define how to construct your string. Maybe it would help you.
Upvotes: 3
Reputation: 4434
You're only printing the first StackTraceElement from the array. You'll want to iterate through that and print each.
for (StackTraceElement elem : trace) {
System.err.println(elem);
}
Upvotes: 5