我正在使用 Apache PdfBox 库,我注意到几乎所有东西都会抛出 IOException,考虑到大多数 IOException 实际上应该是非法状态异常,处理起来非常烦人,但似乎 apache 希望客户端处理它,所以他们强制它们作为受检查的异常。无论如何...
我的问题是,如何将 IOException 包装到扩展 RuntimeException 的自定义异常中,以便 API 更容易处理?
示例:
private final PDDocument document;
private final PDPage page;
private final PDFont font;
public PdfBoxWrapper(PDDocument document, PDPage page, PDFont font)
{
this.document = document;
this.page = page;
this.font = Objects.isNull(font) ? PDType1Font.HELVETICA : font;
this.document.addPage(this.page);
try
{
this.canvas = new PDPageContentStream(this.document, this.page);
}
catch (IOException exception) {
logger.error(exception.getMessage());
}
}
请注意我如何将 PDPageContentStream 包装在 try catch 中。如何将 PdfBox 中的 IOException 包装为 PdfBoxIllegalStateException ?
如下图:
public class PdfBoxIllegalStateException extends RuntimeException
{
public PdfBoxIllegalStateException(String message)
{
super(message);
}
public PdfBoxIllegalStateException(String message, Throwable cause)
{
super(message, cause);
}
}
最佳答案
您可以捕获IOException
,然后将其包装在PdfBox IllegalStateException
中,然后再次抛出它。
private final PDDocument document;
private final PDPage page;
private final PDFont font;
public PdfBoxWrapper(PDDocument document, PDPage page, PDFont font)
{
this.document = document;
this.page = page;
this.font = Objects.isNull(font) ? PDType1Font.HELVETICA : font;
this.document.addPage(this.page);
try
{
this.canvas = new PDPageContentStream(this.document, this.page);
}
catch (IOException exception) {
logger.error(exception.getMessage());
throw new PdfBoxIllegalStateException(exception);
}
}
关于java - 如何将 IOException 作为自定义运行时异常 Java 8 吞下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719728/