【发布时间】:2019-01-07 16:59:44
【问题描述】:
我刚刚读到,在 Java 中,PrintStream 和 PrintWriter 类不会抛出已检查异常。相反,他们使用了一种错误标志,我可以通过调用 boolean checkError() (API link) 方法读取它。
现在,我问自己如何找出异常发生的原因。有异常的信息有时可能不够,或者?
【问题讨论】:
标签: java printwriter printstream
我刚刚读到,在 Java 中,PrintStream 和 PrintWriter 类不会抛出已检查异常。相反,他们使用了一种错误标志,我可以通过调用 boolean checkError() (API link) 方法读取它。
现在,我问自己如何找出异常发生的原因。有异常的信息有时可能不够,或者?
【问题讨论】:
标签: java printwriter printstream
Based on the source code,看起来他们丢弃了异常。所有的 catch 块如下所示:
try {
...
}
catch (IOException x) {
trouble = true; // (x is ignored)
}
因此,最直接的解决方案可能是尽可能不使用PrintStream。
一种解决方法可能是扩展PrintStream 并将输出包装在另一个OutputStream 中,该OutputStream 在PrintStream 捕获(并丢弃)它之前捕获异常。像这样的:
package mcve.util;
import java.io.*;
public class PrintStreamEx extends PrintStream {
public PrintStreamEx(OutputStream out) {
super(new HelperOutputStream(out));
}
/**
* @return the last IOException thrown by the output,
* or null if there isn't one
*/
public IOException getLastException() {
return ((HelperOutputStream) out).lastException;
}
@Override
protected void clearError() {
super.clearError();
((HelperOutputStream) out).setLastException(null);
}
private static class HelperOutputStream extends FilterOutputStream {
private IOException lastException;
private HelperOutputStream(OutputStream out) {
super(out);
}
private IOException setLastException(IOException e) {
return (lastException = e);
}
@Override
public void write(int b) throws IOException {
try {
super.write(b);
} catch (IOException e) {
throw setLastException(e);
}
}
@Override
public void write(byte[] b) throws IOException {
try {
super.write(b);
} catch (IOException e) {
throw setLastException(e);
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
super.write(b, off, len);
} catch (IOException e) {
throw setLastException(e);
}
}
@Override
public void flush() throws IOException {
try {
super.flush();
} catch (IOException e) {
throw setLastException(e);
}
}
@Override
public void close() throws IOException {
try {
super.close();
} catch (IOException e) {
throw setLastException(e);
}
}
}
}
【讨论】: