try 및 catch 블록 사용

코드에 조건문을 추가하여 보고서 서버에 잘못된 요청을 제한한 후에는 try/catch 블록을 사용하여 적절한 예외 처리를 제공해야 합니다. 이 기술은 유효하지 않은 요청에 대한 또 다른 보호 계층을 제공합니다. 보고서 서버에 대한 요청이 try 블록에 연결되어 있고 해당 요청으로 인해 보고서 서버가 예외를 throw한다고 가정해 보겠습니다. 예외가 catch 블록에서 catch되므로 애플리케이션이 예기치 않게 종료되지 않습니다. 예외가 catch되면 예외를 사용하여 사용자에게 다른 작업을 수행하도록 지시할 수 있습니다. 또는 사용자에게 친숙한 방식으로 오류가 발생했음을 알릴 수 있습니다. 그런 다음 최종 블록을 사용하여 리소스를 클린 수 있습니다. 이상적으로는 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");  
      }  
   }  
}  

Reporting Services의 예외 관리 소개
Reporting Services SoapException 클래스