Reputation: 71
I use System.Data.SQLite in my project. When there is no System.Data.SQLite dll in output folder I can't catch FileNotFoundException (other exception catched fine). Here is the code exapmle:
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
SQLiteConnection conn = new SQLiteConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox doesn't showed. If I extract this code in separate function and wrap this function call in try catch than catching exception work fine and MessageBox showed:
private void DeclareConnection()
{
SQLiteConnection conn = new SQLiteConnection();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
DeclareConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What is the problem?
Upvotes: 4
Views: 345
Reputation: 30883
In the first case you cannot catch the exception because the jit throws the exception as soon as it hits the method. In the second case it jits your method and the exception is thrown by the time it tries to jit the DeclareConnection
method.
Upvotes: 0
Reputation: 3804
You will have to handle the AppDomain.AssemblyResolve event,
Subscribe to the AssemblyResolve event
AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve;
here is some example code that handles the loading of x86 / x64 SQLite assemblies in c#
public static Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name.Contains("System.Data.SQLite"))
{
if (_assembliesResolved)
return null;
Assembly returnValue;
string executingAssemblyPath = Assembly.GetExecutingAssembly().Location;
executingAssemblyPath = Path.GetDirectoryName(executingAssemblyPath);
if (Environment.Is64BitProcess)
executingAssemblyPath = Path.Combine(executingAssemblyPath, @"lib-sqlite\x64\", "System.Data.SQLite.dll");
else //32 bit process
executingAssemblyPath = Path.Combine(executingAssemblyPath, @"lib-sqlite\x86\", "System.Data.SQLite.dll");
returnValue = Assembly.LoadFrom(executingAssemblyPath);
_assembliesResolved = true;
return returnValue;
}
return null;
}
Upvotes: 3
Reputation: 3910
You cannot catch exceptions generated by the fact that a refereced assembly was not found.
Only if you manually load the assembly with Reflection you could catch the exception.
To check if the sqlite assembly is there, do a File.Exists()
.
Upvotes: 0