gpt4 book ai didi

c# - 如何告诉应用程序在抛出异常后停止处理

转载 作者:行者123 更新时间:2023-11-29 08:00:03 25 4
gpt4 key购买 nike

我的应用程序已设置为连接到 MySQL 数据库。当它在线时它表现得很好。我的查询是,当它处于脱机状态时,即使在消息框中显示“无法连接到数据库”异常消息后,Visual Studio 也会引发异常。

我将连接参数放在自己的类中。大多数声明都是在公共(public)类声明下进行的。

// Command to open connection to database
public bool OpenCon()
{

try
{
con.Open();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
//I was hoping to get the application to stop processing further after it failed to connect here.
}

}

// Command to close connection to database
public bool CloseCon()
{
try
{
con.Close();
return true;
}

catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;

}

}

// This method is triggered by the 'signup_Click' event in the signup window
public void Join(signup Signup)
{
// We now have the existing login window as "Signup".

//Query to excecute
query = "insert into temp.signup (member, first, second, third, surname, sex, ......) values ('" + Signup.member.Text + "', '" + Signup.first.Text + "','" + Signup.second.Text + "','" + Signup.third.Text + "','" + Signup.surname.Text + "', '" + Signup.sex.Text + "',....... );";
//Declarations
MySqlDataReader rdr;
cmd = new MySqlCommand(query, con);



// Excecution
try
{
//Open the connection
OpenCon();

//Excecute the command
//This is where the exception is thrown when the computer is offline, by the data reader.
rdr = cmd.ExecuteReader();
//Show the confirmation message
Xceed.Wpf.Toolkit.MessageBox.Show("Saved");

//CLose the connection
CloseCon();
}
//If this fails, catch the exception
catch (MySqlException ex)
{
//And show it in a messagebox
MessageBox.Show(ex.Message);
CloseCon();
}
}

我显然错了,因为这种情况正在发生,但我的印象是,在使用 return 关键字退出方法后处理就会停止,或者默认情况下抛出异常时会停止。

所以我的问题是,如果“OpenCon”方法返回 false(无法连接到数据库),如何告诉它停止继续前进?

我希望它不要抛出第二个异常来暂停我的应用程序,而只是等待进一步的指令。

最佳答案

你可以做到

if(OpenCon())
{
//Excecute the command
//This is where the exception is thrown when the computer is offline, by the data reader.
rdr = cmd.ExecuteReader();
//Show the confirmation message
Xceed.Wpf.Toolkit.MessageBox.Show("Saved");

//CLose the connection
CloseCon();
}

很高兴您有一个 bool 返回值,检查它并采取进一步的操作。

关于c# - 如何告诉应用程序在抛出异常后停止处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24062287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com