分享方式:


使用 try 和 catch 區塊

將條件語句新增至程式碼來限制報表伺服器的無效要求之後,您應該使用 try/catch 區塊來提供適當的例外狀況處理。 這項技術針對無效的要求提供另一層保護。 假設對報表伺服器的要求會包裹在 try 區塊中,而且該要求會導致報表伺服器擲回例外狀況。 在 catch 區塊中攔截到例外狀況,因而防止應用程式意外結束。 一旦攔截到例外狀況,您可以使用例外狀況來指示使用者以不同的方式執行動作。 或者,您可以透過易記的方式讓使用者知道發生錯誤。 接著您可以使用 Finally 區塊來清除任何資源。 理想上,您應該產生一般的例外狀況處理計劃,來避免 Try/Catch 區塊不必要的複製。

下列範例使用 Try/Catch 區塊來增強例外狀況處理程式碼的可靠性。

// C#  
private void PublishReport()  
{  
   int index;  
   string reservedChar;  
   string message;  
  
   // Check the text value of the name text box for "/",  
   // a reserved character  
   index = nameTextBox.Text.IndexOf(@"/");  
  
   if ( index != -1) // The text contains the character  
   {  
      reservedChar = nameTextBox.Text.Substring(index, 1);  
      // Build a user-friendly error message  
      message = "The name of the report cannot contain the reserved character " +  
         "\"" + reservedChar + "\". " +  
         "Please enter a valid name for the report. " +  
         "For more information about reserved characters, " +  
         "consult the online documentation";  
  
      MessageBox.Show(message, "Invalid Input Error");  
   }  
   else // Publish the report  
   {  
      Byte[] definition = null;  
      Warning[] warnings = {};  
      string name = nameTextBox.Text;  
  
      try  
      {  
         FileStream stream = File.OpenRead("MyReport.rdl");  
         definition = new Byte[stream.Length];  
         stream.Read(definition, 0, (int) stream.Length);  
         stream.Close();  
         // Create report with user-defined name  
         rs.CreateCatalogItem("Report", name, "/Samples", false, definition, null, out warnings);  
         MessageBox.Show("Report: {0} created successfully", name);  
      }  
  
      // Catch expected exceptions beginning with the most specific,  
      // moving to the least specific  
      catch(IOException ex)  
      {  
         MessageBox.Show(ex.Message, "File IO Exception");  
      }  
  
      catch (SoapException ex)  
      {  
         // The exception is a SOAP exception, so use  
         // the Detail property's Message element.  
         MessageBox.Show(ex.Detail["Message"].InnerXml, "SOAP Exception");   
      }  
  
      catch (Exception ex)  
      {  
         MessageBox.Show(ex.Message, "General Exception");  
      }  
   }  
}