[英]how to tell app to stop processing after exception is thrown
我的應用程序設置為連接到MySQL數據庫。 聯機時它可以正常運行。 我的查詢是脫機時,即使在消息框中顯示“無法連接到數據庫”異常消息后,Visual Studio也會引發異常。
我將連接參數放在自己的類中。 大多數聲明是根據公共類聲明進行的。
// 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();
}
}
我顯然是錯的,因為這正在發生,但是我給人的印象是,在您使用返回關鍵字退出該方法之后,處理停止了,或者默認情況下,當引發異常時,處理停止了。
所以我的問題是,如果“ 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();
}
很好,您有一個布爾返回值,請檢查該值並采取進一步的措施。
如果引發異常,則應用程序不會終止。 用外行術語來說,如果未在應用程序中的任何地方捕獲到異常,則應用程序將被CLR強制終止。 由於您已經處理了異常並且沒有重新拋出它,因此CLR假定您已經“處理”了異常,然后繼續執行其余的代碼。
我假設您要在catch塊中強制終止該應用程序。 這是非常糟糕的做法,並且超出了異常處理的全部目的。 您應該正常地通知用戶,然后繼續執行其他方案。 但是,為了您的知識,您可以使用Environment.FailFast
強制立即退出應用程序。 不建議這樣做,因為它即使不執行任何finally塊也可以立即終止應用程序,因此應避免使用,除非這是災難性的失敗。
最好拋出一個自定義異常並使其冒泡,以便您可以在UI層中安全捕獲它,從而通知用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.