2013-03-04 62 views
4

我在我的項目中使用System.Data.SQLite。當輸出文件夾中沒有System.Data.SQLite dll時,我無法捕獲FileNotFoundException(其他異常捕獲正常)。這裏是代碼exapmle:System.Data.SQLite的FileNotFoundExceptions未捕獲

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     try 
     { 
      SQLiteConnection conn = new SQLiteConnection(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

MessageBox沒有顯示。如果我提取單獨的函數代碼幷包裝在嘗試捕捉調用這個函數比捕捉異常做工精細和消息框顯示:

private void DeclareConnection() 
    { 
     SQLiteConnection conn = new SQLiteConnection(); 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     try 
     { 
      DeclareConnection(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

問題是什麼?

回答

0

您無法捕獲由於找不到引用的程序集而生成的異常。

只有當您手動加載具有反射的程序集時,才能捕捉到異常。

要檢查sqlite程序集是否在那裏,請執行File.Exists()

3

你將不得不處理AppDomain.AssemblyResolve事件,

訂閱AssemblyResolve事件

AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve; 

這裏是處理中的x86/x64的SQLite的組件加載在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; 
    } 
0

在第一種情況下,您無法捕獲異常,因爲只要它遇到方法,jit就會引發異常。在第二種情況下,它會觸發你的方法,當它嘗試使用方法時拋出異常。