C # Exception Handling - How?

Using OCR MODI (Microsoft Office Document Imaging), sometimes the image does not contain text. Therefore, doc.OCR throws an exception.

    public static string recognize(string filepath, MODI.MiLANGUAGES language = MODI.MiLANGUAGES.miLANG_RUSSIAN, bool straightenimage = true)
    {
        if (!File.Exists(filepath)) return "error 1: File does not exist";
        MODI.Document doc = new MODI.Document();
        doc.Create(filepath);

        try
        {
            doc.OCR(language, false, false);
        }
        catch
        {
            //
        }
        MODI.Image image = (MODI.Image)doc.Images[0];

        string result="";
        foreach (MODI.Word worditems in image.Layout.Words)
        {
            result += worditems.Text + ' ';
            if (worditems.Text[worditems.Text.Length - 1] == '?') break;
        }


        doc.Close(false);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(image);
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(image);
        image = null;
        doc = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();

        return result;

    }

This code terminates the application, not what I need: (

How can I just make it disappear like nothing happened?

+3
source share
2 answers

You are 95% of the way with the code you sent:

try
{
    doc.OCR(language, false, false);
}
catch
{
    // Here you would check the exception details
    // and decide if this is an exception you need
    // and want to handle or if it is an "acceptable"
    // error - at which point you could popup a message
    // box, write a log or doing something else
}

It would be wise to catch the type of exception that occurs when the document is empty and then has a different exception handler for any other errors that may occur.

try
{
    doc.OCR(language, false, false);
}
catch (DocumentEmptyException dex)
{
}
catch
{
}

DocumentEmptyException, I believe, did not select the type of exception - if you look at the documents for the OCR method (or through debug), you can determine what type of exception to catch

EDIT ( )

, doc.OCR(...)? catch, ?

, catch:

MODI.Image image = (MODI.Image)doc.Images[0];

, ( catch ), ?

+2

catch, , . , doc, .OCR , , . , doc.Images[0], , , OCR . , , -, try/catch.

+1

Source: https://habr.com/ru/post/1784071/


All Articles