views:

46

answers:

1

Suppose you have created an instance of a Window class. The window is shown to the user. Then, an exception is thrown, and reference to the instance is lost, but the window is still seen by the user because the instance still exists (it's just not referenced anymore).

What to do in these circumstances?

I'm specifically talking about the Squirrel scripting language (http://www.squirrel-lang.org/). Contrary to Java, it doesn't seem to have finally blocks or finalizer methods, so is exception handling broken in this language?

A: 

I don't know squirrel, but even in the absence of a finally block you could simulate the behaviour to some extent within Java:

Exception error = null;
try {
 // do something
}
catch (Exception e) {
  error = e;
}
// My finally code goes here
// ...
if (error != null) {
  // Oh dear clean up all my resources - files, windows, sockets etc.
  throw error;
}

So the catch block stores the exception in a variable that you can test later if you want to rethrow it, and it still allows you the chance to do other cleanup. Obviously there are nuances that you have to be aware of (e.g. explicit kinds of exception that need special handling, more exceptions being thrown outside the try / catch) but with careful consideration you should be okay.

System resources (like graphics handles, sockets, windows, file handles etc.) in particular tend to be a bit messy in Java and other garbage collected languages. Usually these resources will be managed by a class with an explicit close() method. So if you know things have fallen in a heap you would normally invoke an explicit close() on the objects to clean them up straightaway. Otherwise the object will cleanup itself during finalization but only during GC which could be a long time coming.

locka
Makes sense. It's only problematic when you rethrow exceptions (code won't reach your `if` statement in that case). And by the way, `finally` in Java would be called even when no exceptions were thrown, so it wouldn't be what I wanted anyway. Turns out your method would be even more useful than `finally`. *sigh* Long live C++/C++0x's memory managament.
n2liquid