0

Is there a specific exception to be thrown if the connection is closed? I'm writing a method that accepts a SqlConenction object and I wanted to check the connection with State property:

public void MyMethod(SqlConnection sql)
    {
        if (sql.State != ConnectionState.Open)
        {
            //Throw the exception
        }
    }
Phate01
  • 2,499
  • 2
  • 30
  • 55
  • Why throw an exception instead of a message and a flag indicating the connection is not open? – apomene Feb 20 '15 at 08:55
  • It smells bad. Could you tell why you need this? – Vitaliy Feb 20 '15 at 08:56
  • If you really want to throw exception, then throw your own customized exception. More about https://msdn.microsoft.com/en-us/library/seyhszts(v=vs.110).aspx – SelvaS Feb 20 '15 at 08:58
  • I have to create a database, so I'm creating a class that do that loading some sql scripts. I haven't created a wrapper because I would have had to deal with `Dispose()`, so the class gets the sql stream from outside – Phate01 Feb 20 '15 at 09:02
  • 2
    @Phate01 You're doing something wrong with connection. You should not hold it opened for long time unless it's really required. Please consider the answers here: http://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice once you're using "using(var c = new connection())..." you'll not have the question how to check that connection is open. – Vitaliy Feb 20 '15 at 09:08

0 Answers0