System.Data.SqlClient Namespace
The exception that is thrown when a warning or error is returned by SQL Server.
This class is created whenever the SQL Server™ .NET Data Provider encounters a situation that it cannot handle. SqlException always contains at least one instance of SqlError.
Messages with a severity level of 10 or less are informational and indicate problems caused by mistakes in information that a user has entered. Severity levels from 11 through 16 are generated by the user, and can be corrected by the user. Severity levels from 17 through 25 indicate software or hardware errors. When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement.
The SqlConnection remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server usually closes the SqlConnection. However, the user can reopen the connection and continue. In both cases, an SqlException is generated by the method executing the command.
For information on the warning and informational messages sent by SQL Server™, see the Troubleshooting section of SQL Server™ Books Online. The SqlException class maps to SQL Server™ severity.
The following example generates an SqlException due to a missing server, and then displays the exception.
void ThrowSqlException ( ) {
string connString = "uid=sa; pwd=; database=northwind; server=badserver";
SqlConnection myConn = new SqlConnection ( connString );
try {
myConn.Open ( );
}
catch ( SqlException myException ) {
SqlErrorCollection myErrors = myException.Errors;
for ( int i=0; i < myErrors.Count; i++ ) {
Response.Write ( "Index #" + i + "<br>" +
"Error: " + myErrors [ ].ToString ( ) + "<br>" );
}
}
}
Public Sub ThrowSqlException ( )
Dim connString As String = "uid=sa; pwd=; database=northwind; server=badserver"
Dim myConn As New SqlConnection ( connString )
Try
myConn.Open ( )
Catch myException As SqlException
Dim myErrors As SqlErrorCollection = myException.Errors
Dim i As Integer
For i = 0 To myErrors.Count - 1
Response.Write ( "Index #" & i & ControlChars.Cr & _
"Error: " & myErrors ( i ).ToString ( ) & ControlChars.Cr )
Next i
End Try
End Sub |
|
C# |
VB |
SqlError SqlErrorCollection