Tuesday, 11 December 2007

Throw your own SqlException

Last week I was faced with a very specific problem; I needed to throw a SqlException. One of my TestFixtures required several tests in which SqlExceptions were thrown, all with different error codes (accessible via [exceptioninstance].number).

The problem was simple: you cannot instantiate a SqlException as you would an object from a class with public constructors. SqlException's construct is internal.

So what do you do? Well - my first pass at this worked for some scenario but not for others. In my tests I would create a SqlConnection instance with a bogus connection string and attempt to open it. This would throw a SqlException.

I set the "Connect Timeout" attribute of the connection string to "1" in order for Connection.Open to time out quickly.

However, this throws a specific SqlException and you really have no control over the state of the exception at all. So if you need to throw a SqlException with a specific error code you're kind of screwed.

Well, not really. This article gives an excellent example of how, using reflection, you can create your own specific SqlException. I've employed this approach with excellent results, and my tests are much faster than when I induced the exceptions with SqlConnections.

No comments: