c# - C# 中的异常处理 - 如何处理?

标签 c# exception

使用 MODI(Microsoft Office 文档成像)OCR,有时图像不包含任何文本。因此 doc.OCR 抛出异常。

    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;

    }

这段代码终止了应用程序,不是我需要的:(

如何让它像什么都没发生一样消失?

最佳答案

您发布的代码已完成 95%:

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
}

也就是说,谨慎的做法是捕获文档为空时发生的异常类型,然后为可能发生的任何其他错误设置不同的异常处理程序

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

我假设 DocumentEmptyException 不是抛出的异常类型 - 如果您查看 OCR 方法的文档(或通过调试),您将能够找出要捕获的异常类型

编辑(看到您的编辑后)

您确定异常是从 doc.OCR(...) 方法中抛出的吗?在您的编辑中,您在捕获后添加了额外的代码,它可能来自那里吗?

例如,catch 之后的行:

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

如果您的文档是空的,因此异常被抛出并被忽略(因为 catch block 中没有任何内容),此行是否继续工作?

关于c# - C# 中的异常处理 - 如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4625448/

相关文章:

c# - 如何在 Gtk# 窗口上绘制一些东西(线、圆等)?

c# - 提高 ASP.NET 应用程序的性能

格式化字符串中的 C# 静态和非静态字符串变量作为参数

java - 遇到异常,发现没有。使用 Apache poi 的 xlsx 文件中的工作表

c# - 比较不同表中的数据并添加到第三个表的最有效方法

c# - C# 中的表达性文本到语音技术

java - 抛出异常java

java - 为什么在对象和 vector 之间进行选择时,Java 的多态性无法捕捉到正确的方法?

google-app-engine - App Engine 中超时异常的名称是什么?

c# - 为什么泛型类型的名称在 .NET 堆栈跟踪中被破坏?