我正在使用Apache的PdfBox库,我注意到几乎所有的东西都抛出了一个IOException,考虑到大多数IOExceptions实际上应该是非法的状态异常,这是相当恼人的,但似乎apache希望客户处理它,所以他们强制他们作为检查异常。不管怎样..。
我的问题是,如何将IOException封装到扩展RuntimeException的自定义异常中,以便更容易处理?
示例:
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);
}
}发布于 2019-04-17 12:12:32
您可以捕获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);
}
}https://stackoverflow.com/questions/55719728
复制相似问题