Exception Handling

Exception Handling

This guide shows how Aspose.PDF FOSS for .NET signals failures through a typed exception hierarchy rooted at PdfException, which itself derives from System.Exception, and how to catch each category of error. Every PDF-specific exception in the library — a bad password, an unreadable file, a missing font, or an invalid form operation — derives from PdfException, so catching PdfException alone is enough to intercept any library-raised error, while more specific catch blocks let you react differently to each failure mode.


Password and Security Errors

InvalidPasswordException is thrown when a password-protected operation is attempted without supplying a valid password, such as opening an encrypted document with the wrong password.

try
{
    var doc = new Document("encrypted.pdf", "wrong-password");
}
catch (InvalidPasswordException ex)
{
    Console.WriteLine($"Password rejected: {ex.Message}");
}

File Format Errors

InvalidPdfFileFormatException is thrown when a stream cannot be opened as a PDF — a bad header, a truncated file, or content that is not recognizable as PDF at all.

try
{
    var doc = new Document("not-a-pdf.txt");
}
catch (InvalidPdfFileFormatException ex)
{
    Console.WriteLine($"Not a valid PDF: {ex.Message}");
}

Font Errors

Font-related failures fall into three distinct exception types, depending on what went wrong:

  • FontNotFoundException — no system font or custom-font source matches the requested font name.
  • UnsupportedFontTypeException — the file supplied as a font is not a recognized font program.
  • IncorrectFontUsageException — a text-showing operator appears in a content stream while no font is set in the current graphics state.
try
{
    var font = FontRepository.FindFont("NonexistentFont");
}
catch (FontNotFoundException ex)
{
    Console.WriteLine($"Font not found: {ex.Message}");
}

try
{
    var font = FontRepository.OpenFont("not-a-font-file.dat");
}
catch (UnsupportedFontTypeException ex)
{
    Console.WriteLine($"Unsupported font file: {ex.Message}");
}

try
{
    var extractor = new PdfExtractor(doc);
    extractor.ExtractText();
}
catch (IncorrectFontUsageException ex)
{
    Console.WriteLine($"Content stream font error: {ex.Message}");
}

Text Extraction Errors

PdfTextDecodingException is thrown when text content cannot be decoded, for example when the encoding referenced by a font is missing or malformed.

try
{
    var extractor = new PdfExtractor(doc);
    extractor.GetText("output.txt");
}
catch (PdfTextDecodingException ex)
{
    Console.WriteLine($"Text decoding failed: {ex.Message}");
}

Form Type Errors

InvalidFormTypeOperationException is thrown when an operation is attempted on the wrong form type — for example, calling an XFA-specific method on a form that is not XFA-based.

try
{
    var form = new Form(doc);
    form.AssignXfa(xmlData);
}
catch (InvalidFormTypeOperationException ex)
{
    Console.WriteLine($"Wrong form type: {ex.Message}");
}

Tips and Best Practices

  • Catch the most specific exception type first (for example, InvalidPasswordException) and add a final catch (PdfException) block only as a fallback for anything else the library raises.
  • Check Form.IsXfa or Form.Type before calling XFA-specific methods to avoid InvalidFormTypeOperationException.
  • Look up fonts with FontRepository.FindFont before rendering so missing fonts can be handled explicitly, rather than relying solely on exception handling.
  • When an unexpected PdfException reaches your top-level handler, build a CrashReportOptions with the caught exception and call ex.GenerateCrashReport(options) to capture a diagnostic report for support requests.
  • Always pass the document password through the Document constructor overload rather than opening the file first and retrying.

Common Issues

IssueCauseFix
InvalidPasswordException on document openWrong or missing password suppliedPass the correct password to the Document(filename, password) constructor
InvalidPdfFileFormatException on document openFile is not a PDF, or is corrupted or truncatedVerify the file header and re-obtain the source file
FontNotFoundException during renderingRequested font is not installed and no substitute is registeredRegister a font source or check FontRepository.Substitutions
UnsupportedFontTypeException from FontRepository.OpenFontSupplied file is not a recognized font programConfirm the file is a valid font before opening it
InvalidFormTypeOperationException on form operationsXFA-specific method called on a non-XFA form, or vice versaCheck Form.IsXfa or Form.Type before calling type-specific methods

FAQ

Should I catch PdfException or the specific subclass?

Catch the specific subclass, such as InvalidPasswordException, when you need to react differently to that failure. Add a final catch (PdfException) block as a fallback for any other library-raised error.

Do all PDF-specific exceptions derive from PdfException?

Yes. PdfTextDecodingException, IncorrectFontUsageException, InvalidPasswordException, InvalidPdfFileFormatException, FontNotFoundException, UnsupportedFontTypeException, and InvalidFormTypeOperationException all derive from PdfException, which itself derives from System.Exception.

What is PdfExceptionMessages for?

PdfExceptionMessages is a static class that centralizes message strings surfaced by the library’s exceptions and security diagnostics, including the DangerousFile message.

Can I generate a diagnostic report when an exception occurs?

Yes. Construct a CrashReportOptions instance with the caught exception, optionally set properties such as ApplicationTitle and CrashReportDirectory, and call GenerateCrashReport(options) on the PdfException to write a detailed crash report.


API Reference Summary

ClassDescription
PdfExceptionBase exception for errors during PDF application execution
PdfTextDecodingExceptionThrown when text content cannot be decoded
IncorrectFontUsageExceptionThrown when a text-showing operator appears with no font set in the graphics state
InvalidPasswordExceptionThrown when a password-protected operation is attempted without a valid password
InvalidPdfFileFormatExceptionThrown when a stream cannot be opened as a PDF
FontNotFoundExceptionThrown when a requested font cannot be located
UnsupportedFontTypeExceptionThrown when a file cannot be opened as a font because its format is unsupported
InvalidFormTypeOperationExceptionThrown when an operation is attempted on the wrong form type
PdfExceptionMessagesCentralized message strings surfaced by the library’s exceptions and security diagnostics

See Also