C# try catch 混淆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19970397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:16:07  来源:igfitidea点击:

C# try catch confusion

c#sqlexception

提问by Nathan

I'm very new to C#.

我对 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 Openor ExecuteNonQuery?
What if I called a bunch of other non-SQLstuff in the Try?
How would I know which failed?
What does SqlExceptionmean over regular Exception?
How would SqlExceptionhandle non-SQL related errors if I had such code in the Tryblock?

我如何知道问题是否发生在Open或 上ExecuteNonQuery
如果我non-SQLTry.
我怎么知道哪个失败了?over
是什么SqlException意思Exception?如果块中有这样的代码,将
如何SqlException处理与非 SQL 相关的错误Try

回答by David Pilkington

You can add multiple catches after the try block

您可以在 try 块之后添加多个捕获

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?

如果我在 TRY 中调用了一堆其他非 SQL 的东西怎么办?我怎么知道哪个失败了?

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.

这将基于操作引发的异常。就像我说的那样,首先捕获最具体的异常,然后在进行时变得更一般。我建议您查看 MSDN 文档,了解您认为可能引发异常的方法。本文档详细说明了在哪些情况下方法会抛出哪些异常。

What does SQLEXCEPTION mean over regular EXCEPTION?

SQLEXCEPTION 对常规 EXCEPTION 意味着什么?

SQLExceptionis an extension of the normal Exceptionclass that is only thrown in certain circumstances.

SQLException是普通Exception类的扩展,只在某些情况下抛出。

SqlException

异常

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

如果我在 TRY 块中有这样的代码,SQLEXCEPTION 将如何处理非 SQL 相关的错误?

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

因此,为了回答您的问题,您设置的块不会捕获任何不是 aSQLException或 extended 的异常SQLException

回答by Eugène

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

快速回答是您可以有许多 catch() 部分来捕获特定的异常。

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.

您真正想做的是将重点放在可能发生的特定异常上的尝试中。您还希望在边界代码(您无法控制发生的事情)周围使用 try-catch 块并优雅地处理您自己的错误。

回答by Marek

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

您可以通过捕获 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.

根据 MSDN:无法在不指定数据源或服务器的情况下打开连接。或 连接已打开。

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

我不建议您将整个Exception messageUI写入UI,因为它更容易被黑客入侵 SQL 数据库

SqlExceptionaccording to MSDN:

SqlException根据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.

每当用于 SQL Server 的 .NET Framework 数据提供程序遇到服务器生成的错误时,就会创建此类。(客户端错误作为标准公共语言运行时异常抛出。)SqlException 始终包含至少一个 SqlError 实例。

回答by Rashedul.Rubel

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 块使用多个 catch 块来处理不同的可能异常。
如果您使用异常并为该异常打印消息,则您的应用程序不会中断,但会显示发生的异常的消息。实际上每个catch块都会定义不同的异常,只有在确定特定类型的异常可能发生时,您才能编写特定异常的catch块。否则声明一个单独的 catch 块,比如catch(Exception ex)它会被任何类型的异常捕获并使用ex.toString()消息跟踪错误。您还可以在 try 块中使用断点来获取导致异常的特定行。

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

谢谢

回答by Christian Mark

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

回答by Kuldeep Kumar

Tryand Catch

尝试捕捉

Actually use in C# Application connect with Data Base

实际使用在 C# 应用程序连接数据库

试试


{


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("您的数据已存储", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);


switch (result)


{


case DialogResult.OK:


清除屏幕();


休息;


}


}


}


}


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

如果您的连接中有任何错误,如配置、程序、参数和初始化,那么他会警告您在这方面的错误