How to prevent Third Party DLL's StackOverflow Exception from killing Main Application?

Viewed 105

We are creating a PDF Preview using PDFToImage DLL of PQScan.We need to create preview image of the first page of PDF.

Whenever I try to get the image, it throws System.StackOverflowException. Which can't be catched in try-catch block and it causes the crash for the application.

try
{
    using (PQScan.PDFToImage.PDFDocument doc = new PQScan.PDFToImage.PDFDocument())
    {
        doc.LoadPDF(UTFPDFPath);
        doc.DPI = 150;
        var temp = doc.PageCount;
    

        using (Bitmap bmp = doc.ToImage(0)) //System.StackOverflowException here
        {
            bmp.Save(BigPrevName, ImageFormat.Gif);
        }
    }
}
catch (Exception ex)
{
}

- $exception {"Exception of type 'System.StackOverflowException' was thrown."} System.StackOverflowException

2 Answers

The short answer here is "no"; a stack-overflow scenario cannot be reliably caught / recovered from.

  • make sure you're on the most recent version available (it might be fixed!)
  • see whether the documentation lists this as a known issue with possible workaround
  • if it is a paid product, ask them to fix it as part of your support
  • if it is open source, consider fixing it yourself and contributing the fix

If none of these are possible, then the fallback would be to write a second executable that just does this processing (using either IPC or file-based means to get data to/from the second process) - then spawn that second process in the knowledge that if it explodes, only the child process has been burned.

As MSDN says using is not designed to catch exceptions because it is actually convenient way to do 'try-finally'. You should change it for something like this:

Bitmap bmp;
try
{
    bmp = doc.ToImage(0);
    bmp.Save(BigPrevName, ImageFormat.Gif);
}
catch (Exception ex)
{
    //process exception
}
finally
{
    if (bmp != null)
      bmp.Dispose();
}
Related