views:

65

answers:

2

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.

+5  A: 
Péter Török
See update - it doesn't appear to do what I want, because the `finally` blocks run first. Am I doing anything wrong?
Daniel Earwicker
@Daniel, see my update.
Péter Török
@Péter Török - I don't think that's right. The inner `catch` executes first and rethrows `x`, but then the `finally` executes and trumps it by throwing new `IOException`, replacing the original. So not only do my `finally` blocks still execute, but my null reference bug is still hidden from the outer layer of code, which only sees `IOException` and so keeps running along happily.
Daniel Earwicker
It also has the drawback that any method following that pattern must be declared with `throws Exception`.
Daniel Earwicker
@Daniel, yes, but you get the stack trace of the inner exception logged - wasn't that the main point? If you really don't want your app to continue, you can call `System.exit()` or do something more suitable instead of rethrowing. You may also catch only `RuntimeException` instead of `Exception` (depending on the actual type of the exception you are hunting) to get rid of the `throws` clause.
Péter Török
The logging is one point, not the main point. The general point is the need to stop `finally` running when the program is out of control, as indicated by an uncaught exception. How can we take the decision to kill the process in the inner code? Suppose I'm a library author - should I be deciding to unilaterally kill the process I'm loading into? The whole point of exceptions is that the response to a failure is decided by `catch` statements on the call stack. One inner level can't take the decision to call it a fatal bug. An outer level can provide a `catch`, which must take precedence.
Daniel Earwicker
@Daniel, apparently I have misunderstood the case a bit, sorry. Are you chasing a concrete bug, or developing a long-term solution to this class of problem? In general, I fully agree about (not) killing the process deep inside a call - my solution would of course be applicable as a temporary workaround only, not for production code. As a long term solution, your only option seems to be not to throw anything from `finally` blocks.
Péter Török
@Peter - I am only just looking at Java again (after a long break) and familiarizing myself with the fundamentals, and at the same time trying to rebuild my understanding of exceptions in the CLR, and this comparison occurred to me. I think you're right: in Java it is simply unsafe to write code that might throw in `finally` blocks. This is a big lost opportunity, of course, as `finally` don't only run in response to exceptions. Exactly the same problem exists in C++ (with destructors in place of `finally` blocks) - see: http://www.gotw.ca/gotw/047.htm
Daniel Earwicker
Though I only think your last comment is right! Your answer as it stands, I don't accept, for the reasons above. Feel free to edit again of course. :)
Daniel Earwicker
A: 

See a tutorial at http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/

cristis
See update - it doesn't appear to do what I want, because the `finally` blocks run first. Am I doing anything wrong?
Daniel Earwicker