tags:

views:

28

answers:

2

Hi all,

im trying to surround my code with exceptions all over so I wont have any memory leaks. I tried the following code, and for some reason the exception isnt being handled and i get runtime error.

some code:

   try
        {
            methodA();
        } catch (Throwable th)
        {
            MsgProxyLogger.error(TAG, th.getMessage());
        }
    }


 protected void methodA()
 {


            Thread disptacherThread = new Thread()
            {

                @Override
                public void run()
                {
                    dispatcher.dispatch(existingMessagesArr);
                }
            };
            disptacherThread.start();
   }  

Now if some runtime exception occurse inside the thread, it wont be caught in the throable clauses ?

why is that? does Anonymous thread is canceling the catch clauses?

Thanks,

ray.

+1  A: 

Unfortunately not.

The try-catch block is able to catch only up to Thread.Start() method (ie. out of memory). But once the thread is started, or better, has been scheduled for start, you will lose control of it.

If an unhandlex exception goes outside the thread scope your JVM will crash. You should surround your inner anonymous method with try-catch.

Hope to have been of help.

djechelon
A: 

Now if some runtime exception occurs inside the thread, it wont be caught in the throwable clauses ?

That is correct. A try / catch can only catch exceptions thrown by the current thread. The code in the anonymous Runnable's run method is executed on a different thread.

There are two solutions to this:

  • Put a try / catch in the run method to deal with the exception.
  • Register an UncaughtExceptionHandler either with the child thread, or its ThreadGroup.

Incidentally, if you are concerned with exceptions causing resource leaks, the best solution is to write your code using this pattern:

    Resource r = // allocate resource
    try {
        // use resource r
    } catch (...) {
        ...
    } finally {
        // release resource r
    }

Simply catching and logging exceptions (as your example code does) will not cure a resource leak.

Stephen C