我正在使用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。如何将IOException从PdfBox包装为PdfBoxIllegalStateException?
如下所示:
public class PdfBoxIllegalStateException extends RuntimeException
{
public PdfBoxIllegalStateException(String message)
{
super(message);
}
public PdfBoxIllegalStateException(String message, Throwable cause)
{
super(message, cause);
}
}
答案 0 :(得分:3)
您可以抓住IOException
,然后将其包裹在PdfBoxIllegalStateException
中,然后再次扔掉。
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);
}
}