0

I have this code

 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {  
        string connstr = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstr);
        conn.Open();
        SqlCommand cmdLoad = new SqlCommand(" *Connection string* ");
        cmdLoad.CommandType = System.Data.CommandType.Text;
        cmdLoad.Connection = conn;
        SqlDataReader rd = cmdLoad.ExecuteReader();
        StringBuilder resultsHtml = new StringBuilder();
        while (rd.Read())
        {
            resultsHtml.Append("<tr class'odd gradeX'>");
            resultsHtml.Append("<td>" + rd["region_location"].ToString() + "</td>");
            resultsHtml.Append("</tr>");
        }
        resultsPlaceHolder.Controls.Add(new Literal { Text = resultsHtml.ToString() });
        rd.Dispose();
        conn.Close();
             }
        catch (Exception ex)
        {
            Response.Write("Cant connect to database");
            throw ex;
        }
    }

In my web.config, I enter the correct connection string and of course it will run and it will execute the try right? However, when I change the connection string (something not in the database) I can't get the Response.Write(); to display something to the browser. How can I display something to the screen if there is an exception in the try?

3
  • You can use Response.Redirect to display another page containing exception message stored in session state, instead of using Response.Write which will write on same page. Commented Jan 27, 2017 at 0:41
  • 1
    Because throw ex is going to interrupt your manual response. The ASP pipelines has its own error handling. Remove the throw ex (it also should be throw, usually - otherwise you wipe the stack strace) Commented Jan 27, 2017 at 0:44
  • You should also consider using a Repeater or other kind of template control to display your data, rather than string-building table rows and dumping them into a Literal. Commented Jan 27, 2017 at 1:02

3 Answers 3

1

It is because of the throw ex; after the Response.Write(). If you take that out things should work as you expect.

Now that this is sorted i suggest a few points :

  • If you are trying to have a custom error handling logic i suggest you check this MSDN article which is a better way of approaching things.
  • When you want to re-throw an exception you should be using throw; instead of throw ex; which will not preserve your stack trace.
  • In cases of failures like the one mentioned in your question, such as failing to connect to the database, you might want to log those exceptions and give appropriate feedback to the end-user which would make sense to them more than :

Cant connect to database

this could be a message saying that the site is experiencing issues and asking them to try again later while someone looks into the issue.

Sign up to request clarification or add additional context in comments.

Comments

0

There are several try/catch patterns. You're using the wrong one

If you wish to completely handle the error and continue This is the one you want

try
{
    DoSomething();
}
catch(SomeException ex)
{
    HandleTheError();
}

If you wish to let the error propagate, but want to add some logic, like logging

try
{
    DoSomething();
}
catch(SomeException ex)
{
    LogTheError(ex);
    throw;
}

If you wish an exception to be thrown, but wish to conceal the internal workings of your code This is the one you used

try
{
    DoSomething();
}
catch(SomeException ex)
{
    LogTheError(ex);
    throw ex;
}

or

try
{
    DoSomething();
}
catch(SomeException ex)
{
    LogTheError(ex);
    throw new OtherException("Custom message");
}

If you wish to swallow the error silently

try
{
    DoSomething();
}
catch(SomeException ex)
{
}

2 Comments

Hi the first code you have catch(SomeException ex) however im sure i did that before, there's a warning that said that ex is declared but never used. so why bother declaring it?
These are just examples. Were this actual code, the catch block could potentially do something with ex, e.g. check its type and take appropriate action.
0

Use the following in your catch:

Response.ClearHeaders();
Response.Write("Cant connect to database");
Response.End();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.