MySQL exceptions not caught (C#)

后端 未结 2 425
渐次进展
渐次进展 2020-12-11 23:48

My C# program works with a MySQL database.

For some reason the program cannot catch exceptions caused my the MySQL connection.

Example:

If I make the

相关标签:
2条回答
  • 2020-12-12 00:03

    Use the appropriate exception type in the catch block.

    Use the appropriate MySQL classes.

    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();
            }
        }
    }
    

    Error Caught No Problem:

    Add References screenshot:

    0 讨论(0)
  • 2020-12-12 00:14

    Catching or handling exceptions in C# generally requires a try-catch statement.

    The syntax is essentially as follows:

    try
    {
        // operation likely to cause error
    } 
    catch (Exception e){
        // handle error
        Console.WriteLine("Exception: " + e);
    }
    
    Console.Read();
    

    So wrap your con.Open() logic in a try-catch statement like so:

    try
    {
        Con.Open();
    } 
    catch (Exception e){
        // handle error
        Console.WriteLine("Possible MySQL Exception: " + e);
    }
    

    Additionally, you can add a finally block to the end of a try-catch statement, which executes its code regardless of whether an exception was handled or not:

        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();
    
    0 讨论(0)
提交回复
热议问题