Brenton Fletcher said:
I have a constructor which starts a thread and I want the thread to throw an
exception in it's run method and then for the constructor to throw the
exception back to the caller of the constructor. Does anyone have any
pointers on this matter ? The exception I am throwing is a checked
exception. I know this might be impossible but I am interested in potential
solutions.
Here's one (very rough) idea:
class A{
A() throws MyExc {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
t.join();
MyExc e = r.getExc();
if(e != null) throw e;
}
}
class MyRunnable implements Runnable{
MyExc exception = null;l
public void run(){
try{
....
}
catch(MyExc e){
exception = e;
}
}
MyExc getExc() { return exception; }
}
If anything the run method of MyRunnable calls throws an exception, the A
constructor can retrieve it and throw it to its caller. But the thread that
calls A's constructor waits for the new thread created in the constructor to
die before it checks whether the new thread caused an exception; we've lost
all of the benefit of an asychronous call and introduced a lot of complexity
in the process.
It shows up a more general problem, though: if you really want to throw an
exception caused by a the run method of a thread out of the method that
spawns that thread, you must: 1) find a way to communicate the exception
from the spawned thread to the creating thread (one approach as I've shown
you), and 2) find a way to make the creating thread wait long enough so that
the spawned thread has a chance to throw any such interesting exception, and
you must do this without losing what you were trying to gain by
multithreading in the first place. (My code above is not a good model for
this.)
I would examine your reasons for wanting to propogate the exception up
beyond the run method of the spawned thread. It might be simpler to
implement some other error notification mechanism than to solve the two
points I outlined above.
How do I reference a class located in a package in a .jar file?
Add the .jar file to your classpath; now the class is referenceable just
like any other packaged class.