Przy użyciu bloków Try i Catch
Po nieprawidłowe żądania serwer raportów jest ograniczone przez dodanie instrukcji warunkowych kodu, należy dostarczyć odpowiedniej obsługi korzystając z bloków try i catch wyjątków.Ta technika stanowi kolejną warstwę ochrony przed żądań, które nie są prawidłowe.Jeśli żądania serwer raportów jest zamontowane w blok try wniosku powoduje, że serwer raport Zgłoś wyjątek, wyjątek wpadł w blok catch, zapobiegając w ten sposób wniosek kończący się nieoczekiwanie.Gdy przechwycono wyjątek można albo Poinstruuj użytkownika, aby inaczej coś zrobić wyjątek lub tylko pozwalają użytkownikowi znać w sposób przyjazny, wystąpił błąd.Następnie można użyć blok finally oczyszczania żadnych zasobów.W idealnej sytuacji należy generować ogólne planu obsługi wyjątków, aby uniknąć niepotrzebnego powielania bloków try i catch.
Poniższy przykład używa bloków try i catch do zwiększenia niezawodności kod obsługi wyjątków.
// 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");
}
}
}
Zobacz także