Question

In the CLR (the runtime used by C#, VB.NET, etc.) there's a way of registering a callback to be called when an unhandled exception is thrown.

Is there anything similar in Java?

I'm guessing it would presumably be some API to which you'd pass an object that implements some interface with a single method. When an exception is thrown and there is no matching catch on the stack, the runtime would call the method on the registered object, and would be passed the exception object.

This would allow the programmer to save the stack trace. It would also allow them to call System.exit, to stop finally blocks executing only for unhandled exceptions.

Update 1.

To illustrate this, here is a sample in C#:

// register custom handler for unhandled exceptions
AppDomain.CurrentDomain.UnhandledException += (sender, evt) =>
{
    Console.WriteLine("unhandled exception");
    Environment.FailFast(null);
};

try
{
    throw new NullReferenceException();
}
finally
{
    Console.WriteLine("finally is executing");
}

The point is that by putting in the call to Environment.FailFast(null) I can stop the finally block from executing.

Sure enough, in NET 3.5 and 4.0 running on Windows 7, I don't see the "finally is executing" string in the output. But if I comment out the FailFast call, then I do see that string in the output.

Update 2.

Based on the answers so far, here's my attempt to reproduce this in Java.

// register custom handler for unhandled exceptions
Thread.currentThread().setUncaughtExceptionHandler(

    new Thread.UncaughtExceptionHandler() {

        public void uncaughtException(
                final Thread t, final Throwable e) {

            System.out.println("Uncaught exception");
            System.exit(0);
        }
    }
);

try
{
    throw new NullPointerException();
}
finally
{
    System.out.println("finally is executing");
}

When I run that in Java 6 (1.6.0_18) I see:

  • finally is executing
  • uncaught exception

In other words, the JRE executes finally blocks before executing the uncaught-exception handler.

For some background on why this is important, here's a more complex example:

try
{
    try
    {
        throw new NullPointerException();
    }
    finally
    {
        System.out.println("finally is executing");
        throw new java.io.IOException();
    }
}
catch (java.io.IOException x)
{
    System.out.println("caught IOException");
}

System.out.println("program keeps running as if nothing had happened...");

So there's a serious bug and I want my program to halt and log the stack trace. But before I can do this, there's an intermediate finally block somewhere on the stack (in a real program it would be in a separate method) and it tries to access the file system. Something goes wrong. Then a little further up the stack suppose I have a catch for IOException because they're not a big deal to me.

Needless to say, the output is:

  • finally is executing
  • caught IOException
  • program keeps running as if nothing had happened...

So now I have by accident created a situation in which serious bugs are hidden from me.

There are two solutions:

  • somehow ensure that finally blocks never throw, because they can't locally tell if it is safe to. This is a shame because it is perfectly okay for them to throw on the normal execution path, i.e. when they are not running in response to a previous exception.
  • tell the runtime that I don't want it to run finally blocks when there's an uncaught exception.

The latter is certainly my preference if it's available.

Was it helpful?

Solution

See Thread.setUncaughtExceptionHandler().

Update: as it turned out, the "unhandled / uncaught exception" seems to mean slightly different things in C# and Java. At first sight, the behaviour you describe seems to be (unfortunately for you) normal in Java:

Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

I.e. the uncaught exception handler is called when the exception has already been propagated out of user code, up into the Thread. This implies that it left the method containing the finally block, which has been duly executed.

AFAIK finally blocks are always run in Java, so your Option 2 is not viable.

Conclusion from the discussion below

Option 1 - not throwing anything in finally blocks -, though limiting, seems to be the only real long term solution.

For plainly the logging part, there is an Option 3 though:

try
{
    try
    {
        throw new NullPointerException();
    }
    catch (Exception x)
    {
        System.out.println("caught Exception" + x.getMessage());
        x.printStackTrace();
        throw x; // keep original behaviour
    }
    finally
    {
        System.out.println("finally is executing");
        throw new java.io.IOException();
    }
}
catch (java.io.IOException x)
{
    System.out.println("caught IOException");
}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top