err*_*ist 2 java multithreading exception-handling exception stderr
有没有办法(无论它有多“hacky”)来检测何时System.err写入Java以便能够在发生这种情况时执行逻辑?— 我目前正在使用Thread(我们称之为SwallowingThread)的自定义子类,它Thread.run()以类似于以下代码的方式在其实现中吞下了许多异常:
public final class SwallowingThread extends Thread {
...
@Override
public void run() {
ServerSocket socket = new ServerSocket(80, 100);
try {
Socket connected = socket.accept();
// Do stuff with socket here
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在我的代码中,我希望能够处理使用;实例时发生的UnknownHostException和IOException情况SwallowingThread。有没有办法在它发生后检测到这种捕获并打印到标准错误?— 我最初尝试编写 aUncaughtExceptionHandler来执行此操作,结果发现它没有捕获异常,因为它们被吞下而不是简单地被例如包裹在 a 中RuntimeException并向前抛出。
当然,解决这个问题的一个“更好”的方法是重新编写类的逻辑,但是有没有不接触 的快速解决这个问题的方法SwallowingThread?
您可以实现从 PrintStream 派生的自己的类(我称之为 DelegatingErrorPrintStream),它会通知您是否有新输出,然后委托给 System.err 现在您可以使用 System.setErr(err) 将您的 DelegatingErrorPrintStream 设置为 System.err 的输出流);
完整示例,包括用法:
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class ErrorNotifierExample {
private static final class ErrorDelegatingPrintStream extends PrintStream {
public ErrorDelegatingPrintStream(PrintStream defaultErr)
throws FileNotFoundException, UnsupportedEncodingException {
super(defaultErr);
}
@Override
public void print(boolean b) {
super.print(b);
notifyListener(b);
}
@Override
public void print(char c) {
super.print(c);
notifyListener(c);
}
@Override
public void print(int i) {
super.print(i);
notifyListener(i);
}
@Override
public void print(long l) {
super.print(l);
notifyListener(l);
}
@Override
public void print(float f) {
super.print(f);
notifyListener(f);
}
@Override
public void print(double d) {
super.print(d);
notifyListener(d);
}
@Override
public void print(char[] s) {
super.print(s);
notifyListener(s);
}
@Override
public void print(String s) {
super.print(s);
notifyListener(s);
}
@Override
public void print(Object obj) {
super.print(obj);
notifyListener(obj);
}
@Override
public PrintStream append(CharSequence csq, int start, int end) {
notifyListener(csq); // TODO will need some special handling
return super.append(csq, start, end);
}
private void notifyListener(Object string) {
// TODO implement your handling here. System.out printing is just an
// example.
System.out.println(String.valueOf(string));
}
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
ErrorDelegatingPrintStream errReplacement = new ErrorDelegatingPrintStream(System.err);
System.setErr(errReplacement);
System.err.println("TEST01");
throw new RuntimeException("just a test output for ERROR handling");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
765 次 |
| 最近记录: |