Skip to content
Advertisement

How to hide a method from Stacktrace but not its exception?

I am facing this situation where I have my method which throws some exception. I mask the exception so that it is not shown what exactly is, however in the stack trace the method it comes from is also shown.

The code is something like this:

public Something methodForHiding() throws Exception {
    try { 
            some code
       }
    catch (Exception e) {
       throw ExcpetionMask.maskExep();
   }
   return Something
}

In the stacktrace I get:

at com.Program.maskedException
at com.Program.methodForHiding

I would like to remove this methodForHiding from the stacktrace and leave only the maskedException

Is there any way to achieve this?

Advertisement

Answer

You can do it as follows:

public class CustomException extends Exception{

    public CustomException() {
        StackTraceElement[] stackTrace = super.getStackTrace();
        StackTraceElement[] newArray = Arrays.stream(stackTrace).filter(i -> i.getMethodName().equals("The method to remove"))
                .toArray(StackTraceElement[]::new);
        super.setStackTrace(newArray);
    }
}

On the constructor of your custom exception edit the stack trace by calling public void setStackTrace(StackTraceElement[] stackTrace).

First get the currently stack trace using public StackTraceElement[] getStackTrace(), then filter the method that you do not want to be shown in the stack, and set the new stack trace accordingly.

Personally, I think it would be better to instead of removing the method simply replace its name by something like

“Method removed from call stack”

to not mislead those that have to look at the stack trace to find out the source a bug.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement