Steve
Steve

Reputation: 1175

JVM - Print Stack trace without explicit call

Is there a way in java to print a stack trace of any exception in a catch block without making code modifications. I was told that there was a JVM arg you could use to produce stack traces of all exceptions for debugging, although I can't find any documentation on this. The only solution I can think of for this is to use aspectj and create an aspect on any exception that is created and print the stack trace. I was hoping there was a better solution than aspects.

Thanks, Steve.

--Edit-- So what I want to find out is lets say I have this code: try { throw new Exception(); } catch (Exception e) { //Ignore exceptions }

I would like to see the e.printStackTrace() even though no call is made to it. This can help with debugging a jvm crash I am seeing, and there is a lot of error hiding going on.

Upvotes: 3

Views: 1894

Answers (2)

FThompson
FThompson

Reputation: 28687

As Marko Topolnik said, logging any exception may take a bit of work, but you can also implement a custom uncaught exception handler to do whatever you please with uncaught exceptions.

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    private final Logger log = Logger.getLogger("EXCEPTION");

    public void uncaughtException(final Thread t, final Throwable e) {
        log.logp(Level.SEVERE, "EXCEPTION", "", "Unhandled exception in thread " + t.getName() + ": ", e);
    }
});

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200138

Better solutions would only exist for unhandled exceptions. There is no first-class support to log any exception, anywhere that happens inside normally functioning code. I would recommend you try with aspects and intercept the Throwable constructor calls, if that's at all possible. If possible, you may still get false positives because instantiating exception does not entail throwing it.

Upvotes: 1

Related Questions