p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   General .NET (http://p2p.wrox.com/forumdisplay.php?f=122)
-   -   C# handling SQL Server exceptions (http://p2p.wrox.com/showthread.php?t=16234)

booksnore2 July 31st, 2004 10:19 AM

C# handling SQL Server exceptions
 
Is there anyway in C# that you can check to see if a table exists in SQL Server? Does anyone know of a good resource for learning how to handle C# exceptions specifically relating to calls to SQL Server?

Also in the code below I get a 'Unreachable code detected' warning if I uncomment the lines
//sqlDataReader.Close();
// cn.Close();

I'm guessing the datareader and the sql connection will be closed automatically after the return statement. Is that correct? Any help much appreciated.


public SqlDataReader GetReportInfo ()
{

String connectionString = GetConnectionString();
//get connection string
SqlConnection cn = new SqlConnection();
cn.ConnectionString = connectionString;
SqlCommand sqlCommand = new SqlCommand("select ReportName from ReportInfoTable",cn);
SqlDataReader sqlDataReader;
cn.Open();
sqlDataReader = sqlCommand.ExecuteReader();
return sqlDataReader;
//sqlDataReader.Close();
// cn.Close();
}

alyeng2000 July 31st, 2004 07:00 PM

General Query Used:
SELECT [name] FROM sysobjects
      WHERE name = 'TableName'
      AND type = 'U'

Ahmed Ali
Software Developer

ratish_aravind September 7th, 2006 11:24 AM

Hi,

Has anyone found a solution for the "unreachable code detected" compilation error ? Iam facing the same problem with reader.
Any suggestions will be greatly appreciated...

Thanks,
Ratish.



adyrotaru September 16th, 2006 09:40 AM

Hi ratish,
The following piece of code will always yield an "unreachable code detected" warning or even an error compiler message (depend on your compiler's warning level settings).

return sqlDataReader;
//sqlDataReader.Close();
// cn.Close();

The reason is because you have an unconditional return statement before the tho so-called "buggy" lines:

//sqlDataReader.Close();
// cn.Close();

The code execution will ALWAYS return before reaching those lines (when uncommented).

I recommend that you ALWAYS set your project's settings to "Treat warnings as errors". Alternatively, NEVER let unsolved warnings in your code as more subtile error may be produced later.

Go to: Project/Properties/Configuration Properties/Buil/Treat Warnings as Errors and set this param to "True".
You also may want to change the Warning level, but I also recommend to leave it to level 4 - the most restrictive. I use this level in conjuction with "Treat Warnings as Errors" = True.





All times are GMT -4. The time now is 06:59 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.