Log external but not own assembly first chance exceptions - c#

Catching Own First Chance Exceptions
AppDomain.CurrentDomain.FirstChanceException += FirstChanceException;
private static void FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
// I would like to log exceptions happening outside my assembly?
// But this event does not receive external FirstChanceExceptions
// (unlike Visual Studio debug output)
myLogger.Log(e.Exception);
}
Example
I would like to log A first chance exception of type 'System.IO.IOException' occurred in WindowsBase.dll
But not log A first chance exception of type 'System.DivideByZeroException' occurred in MyApp.exe
Solution?
Is there a way to get notified of those exceptions arising in dlls such as mscorlib.dll?
Note the interest is to log in the production release, not only in debugging.
Why
Exceptions that occur in external dll dependencies can cause trouble, even if they are handled there.
For example, due to an exception a null value may be returned from an external method (instead of returning the desired output of x) and even though my code mostly handles such abnormal output it is useful to know what exactly went wrong and where - because while I may be able to avoid fatal exceptions then more often than not that null value makes part of my app non-functional. So logging the external first chance exception would provide valuable information to help rectify the issue / turn that null into x. And this may be present in only given environments / for specific users etc...

You can use StackTrace class to check what is the source of the exception:
var stackTrace = new StackTrace(e.Exception);
var sourceFrame = stackTrace.GetFrame(0);
var throwingMethod = sourceFrame.GetMethod();
var sourceAssembly = throwingMethod.DeclaringType.Assembly;
var assemblyName = sourceAssembly.GetName().Name;
bool isMyApp = assemblyName == "MyApp";

Related

Catch All Unhandled Exceptions

I'm going to catch all unhandled exceptions in my Winforms app. Here is the shortened code:
[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();
}
The issue is that sometimes FormName, LineNumber and ColumnNumber are not correctly returned. Here is the result that I sometimes get:
--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
As you can see, LineNumbers and ColumnNumbers are 0. FormName is System.Linq.Enumerable ...
How can I solve the problem?
How can I solve the problem?
When no .pdb is present for a given module, the stack trace information will necessarily not be able to include file names, line, or column numbers.
To get them, you need to make sure you have the .NET .pdb available and loaded. There are a number of resources available which describe how to do this. See Cannot step into .NET framework source code, for example, or Advanced .NET Debugging - PDBs and Symbol Stores. You can use your favorite web search engine to find additional resources.
I'll note also that you are describing the type name as the "FormName", which is incorrect. It's only the form name when the exception was in fact thrown by your form. Unhandled exceptions are always bugs, and as such are very often thrown by framework or other library code, and the types won't be forms.
I will also mention that catching all exceptions is useful only for diagnosing bugs. This should not be used as an attempt to improve general reliability of a program (except to the extent that better diagnosis can allow you to fix bugs). When an unhandled exception occurs, you should log it and then kill the process. Allowing a process to continue executing after an unhandled exception occurs is dangerous for your data, and can lead to complacency with respect to bug-fixing.

How can I handle the exception which throws on an external dll?

I have developed a project which uses an external dll as FTPServer, I have created the FTP Server on my project like this:
private ClsFTPServer _ClsFTPServer;
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
The Code above creates an instance of FTP server class, the class starts the FTPserver on it's constructor, it works fine independently as a module while the clients send their request correctly, but when an incorrect request comes to FTP server it throws an exception and cause my application to crash.
How can I handle the exception thrown by the external dll to prevent my application from crashing?
I recently answered a similar (ish) question which may prove useful -
Catch completely unexpected error
EDIT. I have to agree with Hans' comment above - might be an idea to find another FTP server.
Just for completeness, here's the appdomain/thread exception setup from - http://msdn.microsoft.com/en-GB/library/system.windows.forms.application.threadexception.aspx
Application.ThreadException += new ThreadExceptionEventHandler (ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
In case of using external unmanaged\unsafe code, .NET (above .net 4) by default cannot handle Memory Access Violation exceptions that happens inside of dll code.
in order to catch these kind of exceptions, there is three things to do. I did them and it worked for me:
Add these Attributes to the method that exception occurred inside of it :
(the method that calls the method of the unmanaged code.)
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
Add this tag to App.Config file below runtime tag :
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
<!-- other tags -->
</runtime>
Catch these kind of exception by using System.AccessViolationException exception type :
try{
//Method call that cause Memory Access violation Exeption
}
catch (System.AccessViolationException exception)
{
//Handle the exception here
}
What i said is just the cure for these type of exception. for more information about this exception's ego and how this approach works, see System.AccessViolationException
You've probably already tried this, but just in case, have you tried wrapping it in a try catch?
try
{
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
...
}
catch(Exception e)
{
...
}
By putting a try...catch block around every call into the object and its methods.
Something like:
try
{
// use the DLL in some way
}
catch (Exception e)
{
// Handle the exception, maybe display a warning, log an event, etc.)
}
Also note that while running under Visual Studio, if you go to the "Debug" menu and select "Exceptions..." it will allow the debugger to break on ALL exceptions if you start your program under the debugger, and not just unhandled exceptions. Just click the 'Thrown' checkbox next to "Common Language Runtime Exceptions".

Unhandled Exception in C# Console Application causing AppCrash

I have a Windows Console application built in Visual Studio 2010 and it keeps crashing but the error is not caught by the visual studio debugging tool nor by try/catch statements in my code.
I have managed to locate the WER file on my system and would like to be able to understand the contents of the file so I can pinpoint exactally what is causing the unhandled exception.
I would be greatful if anyone can offer some idea on how I can use the following information to locate the process causing me this problem and also what the exception may be...
The information from the WER file is:
Version=1
EventType=APPCRASH
EventTime=129973086237604286
ReportType=2
Consent=1
ReportIdentifier=91331e8b-2dc8-11e2-977b-080027f7e5bb
IntegratorReportIdentifier=91331e8a-2dc8-11e2-977b-080027f7e5bb
WOW64=1
Response.type=4
Sig[0].Name=Application Name
Sig[0].Value=SAGE_TESTING.vshost.exe
Sig[1].Name=Application Version
Sig[1].Value=10.0.30319.1
Sig[2].Name=Application Timestamp
Sig[2].Value=4ba2084b
Sig[3].Name=Fault Module Name
Sig[3].Value=ntdll.dll
Sig[4].Name=Fault Module Version
Sig[4].Value=6.1.7600.16385
Sig[5].Name=Fault Module Timestamp
Sig[5].Value=4a5bdb3b
Sig[6].Name=Exception Code
Sig[6].Value=c015000f
Sig[7].Name=Exception Offset
Sig[7].Value=000845bb
DynamicSig[1].Name=OS Version
DynamicSig[1].Value=6.1.7600.2.0.0.272.7
DynamicSig[2].Name=Locale ID
DynamicSig[2].Value=2057
DynamicSig[22].Name=Additional Information 1
DynamicSig[22].Value=0a9e
DynamicSig[23].Name=Additional Information 2
DynamicSig[23].Value=0a9e372d3b4ad19135b953a78882e789
DynamicSig[24].Name=Additional Information 3
DynamicSig[24].Value=0a9e
DynamicSig[25].Name=Additional Information 4
DynamicSig[25].Value=0a9e372d3b4ad19135b953a78882e789
Here is the section of code I believe to be causing the exception to be thrown:
//Data from the project linked to the split data
if (oSplitData.Project != null)
{
oProject = oSplitData.Project as SageDataObject190.Project;
oBasicDetail.ProjectID = oProject.ProjectID;
oBasicDetail.ProjectReference = oProject.Reference.ToString();
}
else
{
oBasicDetail.ProjectID = -1;
oBasicDetail.ProjectReference = "NO_PROJECT";
}
To add to all the above I seem to have found that there is a general exception that is being thrown but it doesn't help me out much - if anyone can put some light on this it would be great:
Unhandled exception at 0x78bc7361 in SAGE_TESTING.exe: 0xC0000005: Access violation reading location 0xfeeefeee.
If your program is multi-threaded and the exception is thrown in one of the spawned threads, the Exception may not be caught depending on how you do exception handling in your program.
You can add a catch-all exception handler like this:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
// Your code here
}
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
Environment.Exit(1);
}
}
UPDATE
Based on the code you posted, here are some things to look at
Put a try/catch block around the code you posted.
Are you sure that oSplitData is not null?
In the following line, oProject will be null if oSplitData.Project is not of type SageDataObject190.Project. Test for null.
oProject = oSplitData.Project as SageDataObject190.Project;
You are probably dealing with so-called corrupted state exceptions. These exceptions corrupt the process in a way so it is usually more safe to kill the process since it is very difficult to impossible to recover from such an error, even if it would be only for running a short catch-clause. Examples are StackOverflowExceptions, OutOfMemoryExceptions or AccessViolationExceptions.
There is an extensive and generally interesting explanation on corrupted state exceptions in this article.
What is helpful on getting a hand on such exceptions is to use DebugDiag. With this tool from Microsoft (download on this page) you can define a crash rule which generates a crashdump for your failed process. You can easily open these dump files in Visual Studio, where you may find the source of the exception that lead to the failure. This is not guaranteed but it often helped me in the past to nail down some nasty errors.
Are you invoking non-managed C++ or other code?
I'd try something like
static void Main()
{
try
{
DoSomethingUseful() ;
}
catch ( Exception e )
{
// managed exceptions caught here
}
catch
{
// non-managed C++ or other code can throw non-exception objects
// they are caught here.
}
return ;
}
See Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?
Also C++ try, catch and throw statements at msdn: http://msdn.microsoft.com/en-us/library/6dekhbbc(v=vs.100).aspx
And MSIL opcode throw (0x7A) allows the throwing any object reference. C#, however, does not allow it.
But it looks like they improved things with .Net 2.0 and started wrapping oddball stuff in an RuntimeWrappedException.

VS2010 did not break debug on static constructor exception

I have a Windows Forms application with a single Editor class (that inherits from Form).
public partial class Editor : Form
{
public Editor()
{
InitializeComponent();
Load += Editor_Load;
}
private void Editor_Load(object sender, EventArgs e)
{
cmbConnections.DataSource = ConnectionManager.Connections;
cmbConnections.Visible = false;
}
}
Other than designer-generated code, this is the only code for the form (that contains only a single Combo Box (cmbConnections).
The ConnectionManager class is a static class with a static constructor. It's constructor does some initialization and then tests for some critical condition. If the condition is met, the constructor throws an exception. However, this exception does not break in the debugging mode in Visual Studio 2010. To test this, I've put only throw new Exception() in the ConnectionManager's static constructor. The ConnectionManager is used and therefor initialized (for the first time) in the Editor_Load event handler. Static constructor is called and exception thrown (visible only in output window). The rest of the Editor_Load event handler (cmbConnections.Visible = false;) is not executed, just as expected.
But what I don't understand is why did my VS2010 swallow the exception? It did not break the debug. It is not enclosed in any try/catch block. It continued with program execution with the main window. It almost seems as if the Editor_Load was executed on another thread.
I can see the messages in output window:
A first chance exception of type 'System.InvalidOperationException' occurred in Editor.exe
A first chance exception of type 'System.TypeInitializationException' occurred in Editor.exe
but the execution simply did not break in debug mode.
Here are some of my options that I believe may influence this behavior:
Project Properties->Build->General-> Optimize code is UNCHECKED.
Tools->Options->Debugging->General-> Enable Just My Code is CHECKED.
In exception settings, the checkbox for the "user-unhandled" is CHECKED.
Am I missing something? Is this behavior normal? I thought that VS2010 will throw on ANY unhandled exception. And here this one is unhandled and still does not break.
I think it is by design that you need to enable Managed (.NET) Exceptions 'Thrown' in the Exceptions Dialog (Ctrl-Alt-E).1
To avoid many spurious (handled) exceptions, I usually try to get close to the point where the initializer will be run and then check that checkbox just before continueing.
Also, if there are loader exceptions, be sure to check the nested inner exceptions or loader information in the exception: the exception itself is usually not that informative. I have frequently had to dig through 2 or more layers of wrapping exceptions in order to get at the actual error.
1 I can only guess as to why that is; My feeling is that the static type initializers are not considered to be run deterministically (many things could trigger it and the order is often undefined; it is just guaranteed that a type's static constructor will have been run before it is used, but it can be used at almost any point in the code, without you knowing or explicitely triggering that).
Therefore, it would be hard for the runtime to establish whether it was 'handled by user code' (no user should expect to handle it, because it doesn't know - deterministically - when the initializer will run).
However, this is conjecture on my part.

Error catching in dynamically generated assembly

I'm having trouble with an application I've written, it's basically creating dynamically generated assemblies based on code input by the user.
It compiles and runs fine, but for some reason, sometimes when an Exception occurs in that compiled assembly, it crashes the main program even though everything is thoroughly coated in try/catch blocks.
I add try/catch blocks to surround the user's code in the generated assembly, and also try/catch around the Invocation of the assembly in my app:
StringBuilder verificationErrors = new StringBuilder();
argz[0] = "hello!";
argz[1] = verificationErrors;
object loResult = null;
try
{
loResult = loObject.GetType().InvokeMember("doThis", BindingFlags.InvokeMethod, null, loObject, argz);
}
catch (Exception p)
{
MessageBox.Show(p.Message);
}
It looks like the error is being thrown outside the scope of my app, so it doesn't know how to catch it or something to that effect... any ideas?
It's possible that the invocation of p.Message is throwing an exception. One would presume that we're using the default Message property, but it could be a custom exception that overrides the Message property.
I would wrap the code in the catch block with a further try...catch, and if it throws an error, just say "An unexpected error occurred", and log whatever you can about it.
If you run the program in debug and instruct Visual Studio to break when an exception is thrown, you should be able to inspect the stack trace and determine which method is throwing the exception.
Go to Debug / Exceptions...
Check the box in front of "Common Language Runtime Exceptions", in column "Thrown"
Click "OK"
Run the program in debug mode

Categories

Resources