Exception Without Stack Trace in Java

Exception without stack trace in Java

It's possible to catch a Throwable object in Java without a stack trace:

Throwable(String message, Throwable cause, boolean enableSuppression,boolean writableStackTrace) 

Constructs a new throwable with the
specified detail message, cause, suppression enabled or disabled, and
writable stack trace enabled or disabled.

public Throwable fillInStackTrace()

Fills in the execution stack trace. This method records within this
Throwable object information about the current state of the stack
frames for the current thread.

If the stack trace of this Throwable is not writable, calling this
method has no effect
.

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html

Is it possible to throw a custom Exception without stack trace?

You could replace the stacktrace with an empty array.

public ReservationException(String message, List<GenericException> failedValidations) {
super(message);
this.setStackTrace(new StackTraceElement[0]);

// Alternative: Keep the method where the exception was thrown.
// this.setStackTrace(Arrays.copyOf(this.getStackTrace(), 1));
}

will only print

com.abc.def.exceptions.ReservationException: Exception thrown with error codes :5965

when Throwable::printStackTrace() is called.

But it is definitely better to configure your logger or spring to not print the stacktrace, as Mark Bramnik suggested since you loose valuable information for troubleshooting by removing the stacktrace.

How can an Exception be created/thrown with no stack trace?

Sometimes, especially when it comes to NullPointers (in my experience), the jvm can optimize the creation and casting of exceptions, and the stack trace is lost (or more correctly, never created). I suspect that your issue is not related to certain java libs, but rather the jvm itself.

If you add this argument when starting your jvm-process you will get your stack traces back, if my suspicion is correct.

-XX:-OmitStackTraceInFastThrow

This has been asked before, look here for more details:

  • NullPointerException in Java with no StackTrace
  • Recurring Exception without a stack trace - how to reset?

Note, that this applies sun/oracle jvm

Throwing an exception without Exception in thread...

The correct way to do this is to set your own, custom, uncaught exception handler:

public static void main(String... argv)
{
Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.err.println(e.getMessage()));
throw new IllegalArgumentException("Goodbye, World!");
}

How to disable stack trace generation in a java program?

There are a few intricate parts of the JVM (at least, Sun's implementation of the JVM) which do not work if stack trace generation is disabled (I saw this in the implementation of some support methods for reflection). So I do not think that stack trace generation can be disabled at all. The Runtime.trace*() methods are about something else (a debugging tool much more thorough than stack traces).

In all generality, any Java code can be transparently analyzed, if only through bytecode instrumentation (bytecode modified with extra instructions when it is loaded). The only known defense against such analysis (I am assuming that you are trying to keep your code internals confidential) is obfuscation. See for instance ProGuard. Obfuscation will make stack traces useless to any over-inquisitive user (and, sadly, it also makes debugging very difficult, for the same reasons).

Is there a way for me to throw an exception without it printing the stack trace?

Since exceptions are important, you could use a logging mechanism like log4j (http://logging.apache.org/log4j/1.2/) and set the logging to a different level when you don't want some exceptions to be printed or log to a file instead of console for example.

If you just don't care about the exception, catch it and do nothing with it (empty catch, which is awful).

Rest - How to send Http Error Response Without Stack Trace

There are many possible solutions and I'm pretty sure an ErrorHandler is a much better way to go.

@GetMapping(value="/{empId}", produces=MediaType.APPLICATION_JSON_VALUE)    
public ResponseEntity<EmployeeInfoItem> getEmployeeInfo(@PathVariable("empId") Integer empId) {
try {
...
} catch (Exception e) {
logger.error( e.getMessage() );
return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY).build();
}
}


Related Topics



Leave a reply



Submit