2011-01-07 58 views
3

使用MODI(Microsoft Office Document Imaging)OCR,有時圖像不包含任何文本。因此doc.OCR引發異常。C#中的異常處理 - 如何?

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; 

    } 

此代碼終止應用程序,不是我所需要:(

如何我只是讓它消逝就像什麼都沒有發生的樣子?

+0

要清楚 - 你只是想忽略異常? – 2011-01-07 12:31:39

+0

拋出什麼異常?你確定這個方法完全拋出嗎? – 2011-01-07 12:31:46

回答

2

您是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 s是,我認爲,沒有異常的類型拋出 - 如果你看一下文檔的OCR方法(或通過調試),你將能夠制定出趕上哪個異常類型

EDIT(看到你的編輯後)

你肯定異常正在從doc.OCR(...)方法拋出?在你的編輯中,你在捕捉之後添加了額外的代碼,它是否可以從那裏傳入?

例如,捕捉後的線:

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

如果你的文件是空的,因此拋出異常,並且忽略(如catch塊有什麼也沒有),這是否行繼續工作?

1

你在catch塊中什麼也沒做,只是吞下非常糟糕的異常。代碼繼續執行,並且您嘗試使用doc變量,但由於.OCR調用失敗,因此稍後會拋出另一個異常。例如,如果OCR失敗,doc.Images[0]可能會崩潰。因此,要麼通過返回某些東西來終止方法的執行,要麼將整個方法放在try/catch塊中。