C# try catch confusion

Nathan picture Nathan · Nov 14, 2013 · Viewed 22.4k times · Source

I'm very new to C#.

When I try catch something like this:

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch(SqlException ex)
{
    MessageBox.Show("there was an issue!");
}

How do I know if the problem happened with the Open or ExecuteNonQuery?
What if I called a bunch of other non-SQL stuff in the Try?
How would I know which failed?
What does SqlException mean over regular Exception?
How would SqlException handle non-SQL related errors if I had such code in the Try block?

Answer

David Pilkington picture David Pilkington · Nov 14, 2013

You can add multiple catches after the try block

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch(SqlException ex)
{
    MessageBox.Show("there was an issue!");
}
catch(Exception ex)
{
    MessageBox.Show("there was another issue!");
}

The important rule here to to catch the most specific exception higher up and the more general ones lower down

What if I called a bunch of other non-SQL stuff in the TRY? How would I know which failed?

This will be based on the exception that is thrown by the operation. Like I say, catch the most specific exceptions first and get more general as you go down. I suggest going to look at the MSDN documentation for methods that you think may thrown an exception. This documentation details what exceptions are thrown by methods in which circumstances.

What does SQLEXCEPTION mean over regular EXCEPTION?

SQLException is an extension of the normal Exception class that is only thrown in certain circumstances.

SqlException

How would SQLEXCEPTION handle non-SQL related errors if I had such code in the TRY block?

So to answer your question, the blocks that you had set up would not catch any exception that was not a SQLException or extended SQLException.