C# try catch confusion

淺唱寂寞╮ 提交于 2021-02-07 12:49:18

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.
}



回答5:


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




回答6:


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



来源:https://stackoverflow.com/questions/19970397/c-sharp-try-catch-confusion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!