未捕获MySQLexception(C#)
我的C#程序适用于MySQL数据库。
由于某种原因,程序无法捕获导致MySQL连接的exception。
例:
如果我使连接字符串中的凭据无效,程序将崩溃(即使在调试器中运行时): http : //imgur.com/SfzkVdW
连接代码是这样的:
using MySQLDriverCS; namespace XXX { public class Data { private static MySQLConnection con; static Data() { string connectionString = new MySQLConnectionString("XXX", "XXX", "XXX", "XXX").AsString; con = new MySQLConnection(connectionString + ";CharSet=utf8"); con.Open(); // For testing the connection con.Close(); } ...
关于如何改进并开始捕捉MySQLexception的任何想法?
我试过在try-catch中的静态构造函数中包装代码。 这没有用。 该程序仍然以同样的方式崩溃。
谢谢。
与try-catch包装器相同的代码。 它仍然失败并出现同样的错误: http : //imgur.com/SfzkVdW
static Data() { try { string connectionString = new MySQLConnectionString("XXX", "XXX", "XXX", "XXX").AsString; con = new MySQLConnection(connectionString + ";CharSet=utf8"); con.Open(); // For testing the connection con.Close(); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
在catch块中使用适当的exception类型。
使用适当的MySQL类 。
using MySql.Data.MySqlClient; // class level var or whatnot: string connString = @"server=theHostName;userid=dbuser123;password=OpenSesame7;database=my_db_name"; public void connect() { try { conn = new MySqlConnection(connString); // read above comments for (conn) conn.Open(); } catch (MySqlException ex) { MessageBoxButtons buttons = MessageBoxButtons.OK; string s="MySqlException: "+ex.ToString(); MessageBox.Show(s,"Error",buttons); } finally { if (conn != null) { //conn.Close(); } } }
错误没问题:
添加参考截图:
在C#中捕获或处理exception通常需要try-catch
语句。
语法基本如下:
try { // operation likely to cause error } catch (Exception e){ // handle error Console.WriteLine("Exception: " + e); } Console.Read();
所以将con.Open()
逻辑包装在try-catch
语句中,如下所示:
try { Con.Open(); } catch (Exception e){ // handle error Console.WriteLine("Possible MySQL Exception: " + e); }
此外,您可以将finally
块添加到try-catch
语句的末尾,该语句执行其代码,无论是否处理了exception:
try { // attempt to do something here con.Open(); } catch (Exception e){ // handle error Console.Writeline("Exception: " + e); } finally { Console.Writeline("This runs no matter if an exception is thrown or not!"); } Console.Read();