放在你不能保证代码运行正常的地方,例如提示用户输入电话号码,而用户输入了一串英文,这样程序就会报错,在这种地方就可以使用异常处理,具体如下:
try
{
提示用户输入一串数据类型为int32的数据;
}
catch(异常处理的展示方式)
{
异常处理的具体内容;
}
这个比较好了解,你看看吧
using (SqlConnection con = new SqlConnection("server=.;database=test;uid=sa;pwd=;")) {
using (SqlCommand cmd = new SqlCommand("insert into [test]([ID]) values(0)", con))
{
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
con.Close();
}
}
}
给你一个例子:
public bool test()
{
try
{
string UserDBConnString = System.Configuration.ConfigurationManager.AppSettings["CaDBConnString"].ToString();
string pSQL = "";
if (Button1.Text.Trim() == "添加")
{
pSQL = "insert into users values('','','')";
}
else if (Button1.Text.Trim() == "修改")
{
pSQL = "update users set name = ''";
}
SqlConnection conn = new SqlConnection(UserDBConnString);
SqlCommand cmd = new SqlCommand(pSQL, conn);
conn.Open();
int i = cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
string hmi = e.Message;
return false;
}
finally
{
conn.Close();
}
}
try{放这}