When to use Microsoft.Data.SqlClient.SqlException vs System.Data.SqlClient.SqlException?

asked4 years ago
last updated4 years ago
viewed11.1k times
Up Vote15Down Vote

I understand that around 2019 Microsoft created Microsoft.Data.SqlClient as their replacement for System.Data.SqlClient. System.Data.SqlClient will be supported ongoing but new dev & features will all be in Microsoft.Data.SqlClient. Both of these libraries have a class named 'SqlException'. Assuming I'm using Microsoft.Data.SqlClient everywhere then presumably relevant exceptions will be of type Microsoft.Data.SqlClient.SqlException, I use a bunch of 3rd-party libraries, how can I be sure whether they'll raise a a Microsoft.Data.SqlClient.SqlException or a System.Data.SqlClient.SqlException? Does this mean in a few cases where I have catch handlers for Microsoft.Data.SqlClient.SqlException I should also check for System.Data.SqlClient.SqlException? Or is there something clever that happens which means I only need to think about Microsoft.Data.SqlClient.SqlException? e.g. I have some old code a bit like I've shown below, written before we started using Microsoft.Data.SqlClient. I fear if I simply change it to use Microsoft.Data.SqlClient then there will be some exceptions that are System.Data.SqlClient.SqlException and my code will no longer notice them.

private static bool HandleSqlExceptionInSomeWay(Exception ex)
    {
        var se = ex as System.Data.SqlClient.SqlException;

        if (se != null)
        {
            // ... do something with the SqlException
            return true;
        }

        return false;
    }

So should I change it to be something like this, i.e. check separately for the different types?

private static bool HandleSqlExceptionInSomeWay(Exception ex)
    {
        // handle old SqlExceptions (e.g. from any old 
        // libraries not using MS package yet)
        var se1 = ex as System.Data.SqlClient.SqlException;

        if (se1 != null)
        {
            // ... do something with the SqlException ...

            return true;
        }

        // handle shiny new SqlExceptions 
        var se2 = ex as Microsoft.Data.SqlClient.SqlException;

        if (se2 != null)
        {
            // ... do something with the SqlException ... 

            return true;
        }

        return false;
    }