Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Stack trace element exception

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+\)
like image 335
M.Jones Avatar asked Feb 06 '26 00:02

M.Jones


2 Answers

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);
}
like image 175
killjoy Avatar answered Feb 08 '26 14:02

killjoy


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.

like image 21
tmucha Avatar answered Feb 08 '26 13:02

tmucha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!