C# try catch confusion
Asked Answered
S

7

7

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?

Seismology answered 14/11, 2013 at 5:42 Comment(2)
You can get line number (not in every case, though) from stack trace, and get stack trace from the exception. But this is very fragile method, don't use it for application logic.Leucopoiesis
try catch is designed exception oriented, so you can track back the exceptions, but not the statements.Froward
M
7

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.

Myrta answered 14/11, 2013 at 5:44 Comment(0)
C
4

You can see in which part of code your Exception occured by catching the Exception of SQL

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch(SqlException ex) // This will catch all SQL exceptions
{
    MessageBox.Show("Execute exception issue: "+ex.Message);
}
catch(InvalidOperationException ex) // This will catch SqlConnection Exception
{
    MessageBox.Show("Connection Exception issue: "+ex.Message);
}
catch(Exception ex) // This will catch every Exception
{
    MessageBox.Show("Exception Message: "+ex.Message); //Will catch all Exception and write the message of the Exception but I do not recommend this to use.
}
finally // don't forget to close your connection when exception occurs.
{

connection.Close();

}

InvalidOperationException:

Acording to MSDN: Cannot open a connection without specifying a data source or server. or The connection is already open.

I do not recommend you to write whole Exception message to the UI as it is more vulnerable for hacking the SQL Database

SqlException according to MSDN:

This class is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError.

Corrientes answered 14/11, 2013 at 5:58 Comment(3)
Are you really trying to concatenate the Exception ex to the string in MessageBox.Show("General exception"+ex);?Tentative
ex.Message would be betterMyrta
InvalidOperationException catch other exceptions thrown by other operation. I dont think that catch will do what he wants.Myrta
C
3

The quick answer is that you can have many catch() portions that catch specific exceptions.

try{
}
catch (SqlException sqlEx)
{
    //deal with sql error
}
catch (NullArgumentException)
{
    //Deal with null argument
}//etc
finally
{
    //do cleanup
}

what you really want to be doing is putting things in the try that focus around a specific exception that could happen. You also want to rather have try-catch blocks around boundary code (where you do not have control over what happens) and handle your own errors elegantly.

Caller answered 14/11, 2013 at 5:48 Comment(0)
Y
0

You can use several catch block for a single try block to handle different possible exceptions.
If you use exception and print message for that exception then your application will not break but will show message for the occurred exception. Actually each catch block will define different exception, and you can write a specific exception's catch block only when you are sure that, the particular type of exception may happen. otherwise declare a single catch block like catch(Exception ex) which will be caught for any kind of exception and track error using ex.toString() message. You can also use a breakpoint in the try block to get particular line which have caused the exception.

try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (NullArgumentException ex)
    {
    //Deal with null argument
     ex.toString();
    }
catch (NumberFormatException ex)
    {
    //Deal with null argument
    ex.toString();
    }
catch(SqlException ex)
   {
    MessageBox.Show("there was an issue!");
   }
catch(Exception ex)
   {
    MessageBox.Show(""+ex.toString());
   }

Thanks

Yam answered 14/11, 2013 at 5:59 Comment(0)
T
0

To further determine the issue, you can have this syntax:

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch(Exception ex)
{
    MessageBox.Show("Error:" + ex.Message); // This will display all the error in your statement.
}
Tentative answered 14/11, 2013 at 6:0 Comment(0)
M
0

With Odbc:

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch (OdbcException ex)
{
    MessageBox.Show("there was an issue!");
}
Mangosteen answered 2/3, 2023 at 11:51 Comment(1)
Try to expand on how your answer addresses the question. It may be helpful to round out your code block with an explanation of how OdbcException in the catch block behaves versus the original SqlException.Seigel
V
-3

Try and Catch

Actually use in C# Application connect with Data Base

Try
{
string conString = ConfigurationManager.ConnectionStrings["ldr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("StuProc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@First", firstname.Text);
cmd.Parameters.AddWithValue("@Last", lastname.Text);
cmd.Parameters.AddWithValue("@Phone", phonebox.Text);
cmd.Parameters.AddWithValue("@Email", emailbox.Text);
cmd.Parameters.AddWithValue("@isC#Intrest", csharExperties.Checked);
cmd.Parameters.AddWithValue("@isJavaIntrest", javaExperties.Checked);
cmd.Parameters.AddWithValue("@isVBIntrest", VBExperties.Checked); con.Open();
cmd.ExecuteNonQuery(); DialogResult result = MessageBox.Show("Your Data are Store", "Succeded", MessageBoxButtons.OK, MessageBoxIcon.Information);
switch (result)
{
case DialogResult.OK:
ClearScreen();
break;
}
}
}
}
catch( Exception ex)
{ MessageBox.Show("Problem's: ", ex.Message);
}
}

If any Error in Your Connection like Configuration , Procedure , Parameter and Initialize then he warn you your mistake in this area

Vanden answered 14/8, 2017 at 13:22 Comment(1)
That looks like a bunch of barely related code, and doesn't actually answer anything in the question.Minima

© 2022 - 2024 — McMap. All rights reserved.