使用 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/