Search code examples
c#wpfwia

Exception not caught by catch


I want to use WIA in my app, with the code shown below. However the exception in the shown in the picture is not caught by the catch block.

WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();

while (hatNochSeiten)
{
    try
    {

        AktiverScanner.Geraet = AktiverScanner.GeraeteInfo.Connect();

        WIA.Item geraetObjekt = null;

        geraetObjekt = AktiverScanner.Geraet.Items[1];
        geraetObjekt.Properties["Bits Per Pixel"].set_Value(1);
        geraetObjekt.Properties["Horizontal Resolution"].set_Value(300);
        geraetObjekt.Properties["Vertical Resolution"].set_Value(300);

        WIA.ImageFile scanDatei = (ImageFile)wiaCommonDialog.ShowTransfer(geraetObjekt, ScannerModel.wiaFormatJPEG, false);

        scanDatei.SaveFile(@"C:\scan_" + System.DateTime.Now.ToString("yyyyMMdd-HHmmss") + "_Seite" + seiten.ToString("000") + ".jpg");

        Marshal.ReleaseComObject(scanDatei);

        var status = (int)AktiverScanner.Geraet.Properties["Document Handling Status"].get_Value();
        hatNochSeiten = (status & AktiverScanner.Eigenschaftlesen(3087)) > 0;


        geraetObjekt = null;
        scanDatei = null;
        seiten++;
    }
    catch (System.Runtime.InteropServices.COMException comEx)
    {
        System.Diagnostics.Debugger.Break();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debugger.Break();
    }

The Debugger breaks with this error, as the scanner is still busy, but the exception should be caught from the second catch block.

enter image description here


Solution

  • Visual Studio displays "Exception Thrown" (Ausgelöste Ausnahme) dialog, when:

    • Unhandled exception is thrown
    • You have enabled "Break When Thrown" in "Exception Settings" for certain exception types and one of these exception types is thrown

    In the latter case, it doesn't prevent the exception to be properly caught by catch block. When you continue debugging (usually by pressing F5 or F10), program execution will properly jump to the beginning of appropriate handling catch block. If you do not want this dialog to appear again for this exception type, uncheck "Break when this exception type is thrown" (Bei Auslösen dieses Ausnahmetyps unterbrechen) option or unchek "System.Runtime.InteropServices.COMException" in Exception Settings window (Menu -> Debug -> Windows -> Exception Settings).

    If the exception is still not caught and there is appropriate catch block, another reason could be mismatch between executed code and actual source code.