在打开表单之前会出现一个未知的异常

m3n*_*haq 0 .net c#

以下代码中会出现异常.你能告诉我这段代码中有什么问题吗?打开表单需要时间.在打开表单之前,将显示catch块中的消息框.我的数据库正在运行,但我不知道为什么它运行不顺畅?请指导......

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace IMS
{
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    // To set up a connection object
    System.Data.SqlClient.SqlConnection con;
    System.Data.OleDb.OleDbDataAdapter da;
    private void Form2_Load(object sender, EventArgs e)
    {
        con = new System.Data.SqlClient.SqlConnection(); 
        // TODO: This line of code loads data into the 'iMSDataSet1.Part_Group'
        //table. You can move, or remove it, as needed.
        this.part_GroupTableAdapter.Fill(this.iMSDataSet1.Part_Group);


        con.ConnectionString = "Data     Source=.\\DataDirectory\\IMS.sdf;Password=ims;Persist Security Info=True";
        //open up a connection to the database
        try
        {
            con.Open();
        }
        catch
        {
            MessageBox.Show("Database Exception");
        }
        //Close up a connection to the database
        con.Close();

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void AddPartGroup_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbCommandBuilder cb;
        cb = new System.Data.OleDb.OleDbCommandBuilder(da);

        //DataRow dRow = 
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

那么,您需要更改处理异常的方式.这个:

catch
{
    MessageBox.Show("Database Exception");
}
Run Code Online (Sandbox Code Playgroud)

不是非常有用.它不仅捕获所有异常(而不仅仅是特定异常); 它忽略了异常本身.至少,使用类似的东西:

catch(Exception e)
{
    MessageBox.Show("Database Exception: " + e.Message);
    // Now log e.ToString() somewhere as well
}
Run Code Online (Sandbox Code Playgroud)

这将帮助您解决出错的问题.顺便说一句,我会尝试不在 UI线程中执行数据库操作,并且通常应该只捕获特定的异常 - 但是您最直接的更改应该是停止忽略正在抛出的异常中的有用信息.

请注意,在你发现异常之后,你就会继续,好像什么都没有 - 实际上这听起来好像是一个致命的错误,而你的应用程序的其余部分很快就会失败.您可能应该强制关闭此应用程序(使用适当的解释),而不是尝试继续处于损坏状态.(其他选项包括重试失败的操作等 - 重要的是不要继续好像一切都好.)