我將在Winforms應用程序中捕獲所有未處理的異常。這裏是縮短的代碼:捕獲所有未處理的異常
[STAThread]
static void Main()
{
if (!AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe"))
{
Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod);
}
Application.Run(new frmLogin());
}
private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t)
{
Exception ex = t.Exception;
StackTrace trace = new StackTrace(ex, true);
var db = new MyDataContext();
Error error = new Error();
error.FormName = trace.GetFrame(0).GetMethod().ReflectedType.FullName;
error.LineNumber = trace.GetFrame(0).GetFileLineNumber();
error.ColumnNumber = trace.GetFrame(0).GetFileColumnNumber();
error.Message = ex.Message;
db.Errors.InsertOnSubmit(error);
db.SubmitChanges();
if (new frmError(ex).ShowDialog() != DialogResult.Yes)
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
問題是,有時FormName,LineNumber和ColumnNumber沒有正確返回。下面是結果,我有時會:
--FormName-- --Line/Column-- --Message--
System.Linq.Enumerable 0 0 Sequence contains no matching element
System.RuntimeMethodHandle 0 0 Exception has been thrown by the target of an invocation.
System.Number 0 0 Input string was not in a correct format.
System.Number 0 0 Input string was not in a correct format.
System.ThrowHelper 0 0 Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
正如你所看到的,LineNumbers和ColumnNumbers爲0窗體名稱是System.Linq.Enumerable ...
我怎樣才能解決這個問題?
您的表單未命名爲「System.Linq.Enumerable」。假設你有一個非零的行號,那麼接下來你會怎麼做呢?如果您擁有System.Linq的正確PDB文件,您仍然不會有包含行號的文件。 .NET程序集的構建設置是「僅限pdb」,就像您自己的項目一樣。一定要測試你的應用程序的發佈版本。 –