我制作了一个抽象线程,在其 run() 方法中处理一些流。我希望能够让子类而不是抽象父类处理这些异常,但我不知道最优雅的方法。现在,我正在做这样的事情:
import org.apache.logging.log4j; // (I use log4j for logging)
public interface Loggable {
Logger getLogger();
}
public abstract class ParentThread extends Thread implements Loggable {
private final static Logger logger =
Logger.getLogger(ParentThread.class); // Logger with no Appenders
@Override
public void run() {
try {
// Do some stuff that throws exceptions
doAbstractStuff();
} catch (SomeSortOfException ex) {
getLogger().error("Oh noes!", ex);
} catch (SomeOtherException ex) {
getLogger().error("The sky is falling!", ex);
}
}
public Logger getLogger() { return logger; }
protected abstract void doAbstractStuff();
}
public class ChildThread extends ParentThread {
@Override
public Logger getLogger() { /* return a logger that I actually use */ }
@Override
public void doAbstractStuff() { /* Implementation */ }
}
我想我应该提到 ChildThread 实际上是我的主窗体的内部类,并且它的记录器属于该窗体。
我想到的另一种方法是
abstract void handleException(Exception ex);
在 ParentThread 中,但是我无法处理来自 ChildThread 的单个异常。