在托管代码中,发生错误时会引发异常。 SMO 方法和属性不会报告返回值中的成功或失败。 相反,异常处理程序可以捕获和处理异常。
SMO 中存在不同的异常类。 可以从异常属性中提取有关异常的信息,例如 Message 提供有关异常的文本消息的属性。
异常处理语句特定于编程语言。 例如,在 Microsoft Visual Basic 中,它是 Catch 语句。
内部异常
异常可以是常规的,也可以是特定的。 常规异常包含一组特定的异常。 可以使用多个 Catch 语句来处理预期错误,并允许剩余的错误落入常规异常处理代码。 异常通常发生在级联序列中。 通常,SMO 异常可能是由 SQL 异常引起的。 检测此情况的方法是连续使用 InnerException 属性来确定导致最终顶级异常的原始异常。
注释
异常 SQLException 在 System.Data.SqlClient 命名空间中声明。
此图显示了通过应用程序层的异常流。
示例:
若要使用提供的任何代码示例,必须选择要在其中创建应用程序的编程环境、编程模板和编程语言。 有关详细信息,请参阅 在 Visual Studio .NET 中创建 Visual C# SMO 项目 ,或在 Visual Studio .NET 中创建 Visual Basic SMO 项目。
在 Visual Basic 中捕获异常
此代码示例演示如何使用 Try...Catch...FinallyVisual Basic 语句捕获 SMO 异常。 所有 SMO 异常都具有 SmoException 类型,并列在 SMO 引用中。 显示内部异常序列以显示错误的根。 有关详细信息,请参阅 Visual Basic .NET 文档。
在 Visual C 中捕获异常#
此代码示例演示如何使用 Try...Catch...Finally Visual C# 语句捕获 SMO 异常。 所有 SMO 异常都具有 SmoException 类型,并列在 SMO 引用中。 显示内部异常序列以显示错误的根。 有关详细信息,请参阅 Visual C# 文档。
{
//This sample requires the Microsoft.SqlServer.Management.Smo.Agent namespace to be included.
//Connect to the local, default instance of SQL Server.
Server srv;
srv = new Server();
//Define an Operator object variable by supplying the parent SQL Agent and the name arguments in the constructor.
//Note that the Operator type requires [] parenthesis to differentiate it from a Visual Basic key word.
op = new Operator(srv.JobServer, "Test_Operator");
op.Create();
//Start exception handling.
try {
//Create the operator again to cause an SMO exception.
OperatorCategory opx;
opx = new OperatorCategory(srv.JobServer, "Test_Operator");
opx.Create();
}
//Catch the SMO exception
catch (SmoException smoex) {
Console.WriteLine("This is an SMO Exception");
//Display the SMO exception message.
Console.WriteLine(smoex.Message);
//Display the sequence of non-SMO exceptions that caused the SMO exception.
Exception ex;
ex = smoex.InnerException;
while (!object.ReferenceEquals(ex.InnerException, (null))) {
Console.WriteLine(ex.InnerException.Message);
ex = ex.InnerException;
}
}
//Catch other non-SMO exceptions.
catch (Exception ex) {
Console.WriteLine("This is not an SMO exception.");
}
}