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:

JavaScript

In the stacktrace I get:

JavaScript

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:

JavaScript

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