Represents the exception that is thrown when an error occurs during data retrieval or manipulation.
public abstract class DbException : Exception
Initializes a new instance of the DbException
class.
Initializes a new instance of the DbException
class with a specified error message.
Initializes a new instance of the DbException
class with a specified error message and a reference to the inner exception that is the cause of this exception.
Gets a collection of name-value pairs that provide additional user-defined information about the exception.
Gets or sets a link to the help file associated with this exception.
Gets a reference to the inner exception that is the cause of the current exception.
Gets an error message that describes the current exception.
Gets or sets the name of the application or the object that causes the error.
Gets a string representation of the immediate frames of the call stack.
Gets the method that throws the current exception.
DbException
is the base class for exceptions thrown by ADO.NET providers. It provides common functionality for exceptions related to database operations.
When you catch an exception that derives from DbException
, you can use the properties of the base class to retrieve information about the error, such as the error message, the source of the error, and the call stack.
Specific ADO.NET providers throw derived classes of DbException
, such as SqlException for SQL Server or OleDbException for OLE DB data sources. These derived classes may expose additional properties specific to their data source.
using System;
using System.Data;
using System.Data.Common;
public class Example
{
public static void Main(string[] args)
{
// Assume connectionString and commandText are defined elsewhere
string connectionString = "YourConnectionStringHere";
string commandText = "SELECT * FROM NonExistentTable;";
using (DbConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
{
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (DbException dbEx)
{
Console.WriteLine($"A database error occurred: {dbEx.Message}");
Console.WriteLine($"Error Source: {dbEx.Source}");
// For specific provider exceptions, you can cast and access more properties
if (dbEx is System.Data.SqlClient.SqlException sqlEx)
{
Console.WriteLine($"SQL Error Number: {sqlEx.Number}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}
}
}