2
votes

I've been trying to add exception handling to my test app, but with no success. My app uses SQLite as database provider.

I'm tring to catch SQLiteException:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new Main());
        }
        catch (System.Data.SQLite.SQLiteException)
        {
            MessageBox.Show("Unable to perform database operation. Database file is missing or corrupt", "Database error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

In my Main form I've got such lines:

        using (DbWrapper db = DbFactory.GetConnection("SQLite").WrapIn<MyDbWrapper>())
        {
            db.Open();

            count = db.ExecuteScalar<int>("SELECT COUNT(*) FROM subject WHERE schedule_id = " + ScheduleList.SelectedValue);
        }

However, if I delete my database file from working directory I'm still getting unhandled exceptions instead of MessageBox window.

System.Data.SQLite.SQLiteException (0x80004005): unable to open database file

I've also tried catching Exception type and AppDomain.CurrentDomain.UnhandledException event, but still got the same behaviour.

I'm not asking for solution, just wondering why is it acting like this? Why am I unable to catch the exception? May it be caused by GC corruption while encountering an exception in using block?

UPDATE: Exception handling works perfectly if I wrap my sql operation code in try-catch block right inside my form method.

UPDATE: Problem was solved by adding ThreadExceptionEventHandler. Any ideas how to catch SQLiteException directly?

Best Regards

1
Where do you "get" these exceptions? As long as you debug, your debugger will jump to the line of the exception. Start your program out of the debugger and it should work. - nvoigt
Well, I do know where and why I'm getting the exception. The question is: why am I unable to catch it? - fakemeta
What happens, do you break into the debugger or does your program, started in release, just crash and burn? - nvoigt
Application crashes with unhandled exception error. - fakemeta

1 Answers

0
votes

Sqlite .NET libraries are ultimately managed wrappers around unmanaged c++ Sqlite assemblies. Although it would be informative to get the actual driver you're using, I am assuming that when you added Sqlite to your project (nuget?) it also added an interop assembly.

When you're dealing with managed wrappers around unmanaged libraries you can sometimes run into cases where you can't catch the exceptions being thrown in the unmanaged code. Sometimes adding the legacy unhandled exception policy in your app.config works but it didn't for me.

http://msdn.microsoft.com/en-us/library/ms228965(v=vs.100).aspx