Exception handling in C# - How?
Using MODI (Microsoft Office Document Imaging) OCR, sometimes the image doesn't contain any 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 do I just make it fade away like nothing happened?
You are 95% of the way there with the code you posted:
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
}
That said it would be prudent to catch the exception type that occurs when the document is empty and then have a different exception handler for any other errors that may occur
try
{
doc.OCR(language, false, false);
}
catch (DocumentEmptyException dex)
{
}
catch
{
}
DocumentEmptyException is, I assume, not the exception type thrown - if you look at the docs for the OCR method (or via debug) you will be able to work out which exception type to catch
EDIT (After seeing your edit)
Are you sure the exception is being thrown from the doc.OCR(...)
method? In your edit you added additional code after the catch, could it be coming from there instead?
For example, the line after the catch:
MODI.Image image = (MODI.Image)doc.Images[0];
If your document is empty and therefore the exception is thrown and ignored (as the catch block has nothing in it), does this line continue to work?
You are doing nothing in the catch block, just swallowing the exception which is very bad. The code continues to execute and you try to use the doc variable but because the .OCR call has failed it is more than possible that another exception is thrown later. For example doc.Images[0]
will probably crash if the OCR has failed. So either terminate the execution of the method by returning something or put the entire method in a try/catch block.
精彩评论