DbException Class

System.Data.Common

Represents the exception that is thrown when an error occurs during data retrieval or manipulation.

Syntax

public abstract class DbException : Exception

Inheritance

Derived Classes

Constructors

Properties

Remarks

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.

Examples

Using a try-catch block to handle database exceptions

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}");
                }
            }
        }
    }
}