Unhandled Exception in C# Console Application causing AppCrash - c#

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.

Related

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".

a method call and avoid the dll not found error all the time if exists

This method below is called when you click save all button.
I want to ask you is there any way to skip the error under the code shown below.
Why I ask this: Some times the pDenemeProxy.dll does not exist in the folder of the code.
Morever it is a windows form application. Has the pDenemeProxy.dll in the references. And the fDenemeProxy facade of pDenemeProxy.dll is only initialized if the mDesTemp not null.
Thank you!
private bool SaveAll()
{
...
..
..
if (this.mDesTemp != null)
{
fDenemeProxy dnm = new fDenemeProxy();
dnm.SaveThisCustomer(1234,"D",true);
}
...
..
return;
}
Error: System.IO.FileNotFoundException: 'pDenemeProxy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
note: .net 2.0 and c#
note: Some people advice to put try catch block but it did not work. I have seen during the debug sessions on VS 2008 that when mDesTemp is null we see again the error declared above.
In some line in your code you are using a method which throws an Exception of type System.IO.FileNotFoundException if the conditions for this erroneous situation are true (i.e. you are trying to access a file which is not possible for some reason).
That's the intended and correct behavior what you are experiencing. Whenever you are getting this error message the error has already been happened and now it's up to you to deal with this new situation. That is what Exception-Handling is all about.
To deal with an error that was caused by an exception (informally speaking) you would have to catch a exception that has been thrown before (formally speaking).
To do that you have to enclose the portion of code (the actual method call that inheres the throwing of the exception) with a so-called try-catch block like this:
private bool SaveAll()
{
...
..
..
if (this.mDesTemp != null)
{
try {
fDenemeProxy dnm = new fDenemeProxy();
dnm.SaveThisCustomer(1234,"D",true);
} catch (FileNotFoundException e) {
// deal with the new situation !
}
}
...
..
return;
}
The meaning of that is very simple and intuitive:
Inside the try-block you are 'securing' a piece of code that is capable of throwing an exception for the case it is doing so. This try - block is then followed by an arbitrary number of catch-block - one for each exception that could be thrown by the secured code.
If you have set up this try-catch block correctly you have achieved that whenever your (secured) code throws an exception the execution flow of your program doesn't end (i.e. you program doesn't crash) but it goes to the aproprirate catch-block where you can do anything to deal with error you have just experienced.
Furthermore if you would look on the internet you will find lots of information on that since exception-handling is a very important concept of programming but what I've tried to explain here is the basic concept which you should try to understand first - it won't get more difficult ;)

Log external but not own assembly first chance exceptions

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";

C# rethrow an exception: how to get the exception stack in the IDE?

There has been discussion here before about the correct way to rethrow an exception. This question, instead, is about how to get useful behavior from Visual Studio when using rethrow.
Consider this code:
static void foo() {
throw new Exception("boo!");
}
static void Main(string[] args) {
try {
foo();
} catch (Exception x) {
// do some stuff
throw;
}
}
The exception that comes out has the correct stack trace, showing foo() as the source of the exception. However, the GUI Call Stack window only shows Main, whereas I was expecting it to show the exception's call stack, all the way to foo.
When there is no rethrow, I can use the GUI to very quickly navigate the call stack to see what call caused the exception and how we got there.
With the rethrow I'd like to be able to do the same thing. Instead, the call stack that the GUI shows is of no use to me. I have to copy the exception details to the clipboard, paste it to Notepad, and then manually navigate to whichever function of the call stack I'm interested in.
By the way, I get the same behavior if I add [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] or if I change the catch to just catch (Exception).
My question is: given that the code I have uses rethrow, can someone suggest a convenient way to navigate the call stack associated with the exception? I'm using Visual Studio 2010.
The debugger breaks at the throw in Main because that exception is unhandled. By default, the debugger will only break on unhandled exceptions. Once you've stopped at Main, the call stack for the original exception from foo is present in the exception, but all of the other context has been lost (e.g. locals, stack/memory state).
It sounds like you want the debugger to break on the throw in foo, so you should tell the debugger to break on first-chance exceptions:
Debug ยป Exceptions... (Ctrl+Alt+E)
Check "Thrown" for the exception types you care about (in this case, Commange Language Runtime Exceptions)
Click OK
Start debugging
In this case, the debugger will break immediately when foo throws an exception. Now, you can examine the stack, locals, etc., in the context of the original exception. If you continue execution (F5), the debugger will break again on the rethrow in Main.
Taking another approach, if you're running VS2010 Ultimate, you can also use IntelliTrace to "debug backwards" to see parameters, threads, and variables at the time of the exception. See this MSDN article for details. (Full disclosure: I work on a team closely related to IntelliTrace).
If you use ReSharper, you can copy exception stacktrace to clipboard, then choose in the menu: ReSharper > Tools > Browse Stack Trace (Ctrl+E,T). It will show stacktrace with clickable locations, so you'll be able to quickly navigate.
(source: jetbrains.com)
This feature is also very useful while digging through logs from users (if stacktraces of exceptions are logged).
Not that you should re-throw but here's a blog post about how to preserve the stack trace, essentially it boils down to this:
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
...
catch (Exception ex)
{
// do something
// ...
PreserveStackTrace(ex);
throw;
}
Mike Stall has given a great and simple solution to your problem:
Mark the methods where you rethrow the exception with the attribute [DebuggerNonUserCode]
The IDE will consider this is not your code and will not break the debugger in such place, and instead will look further in the stack, showing the next rethrow or the initial exception place.
(if the next rethrow is also annoying, mark it as [DebuggerNonUserCode] as well, etc...)

What happens if my IExceptionPublisher throws an Exception?

I'm using the .NET Exception Management Application Block (EMAB).
As part of this I am implementing IExceptionPublisher classes.
However, I am wondering what happens if these publishers encounter an Exception.
I had a bit of a look around and apparently they are meant to do something like this:
try
{
/* Normal Exception Publishing */
}
catch
{
ExceptionManager.PublishInternalException(exception, additionalInfo);
}
Source:
One caveat: what happens if there is
an exception in our custom publisher
code, preventing the publishing to
MSMQ? For that, we turn to the
ExceptionManager.PublishInternalException
method, which will publish the
exception to the default publisher,
which is the Windows application event
log.
However, PublishInternalException is both protected and internal so I would have to be implementing ExceptionManager, not IExceptionPublisher, to access it.
It handles itself, publishing both the original Exception and the Exception your IExceptionPublisher threw to the Application Log
The idea to manually call PublishInternalException must have been related to an early beta. The current ExceptionManager wraps the IExceptionPublisher calls in its own try-catch which calls PublishInternalException itself. If you check out the code in Reflector it basically does this:
/* Foreach publisher */
Exception originalException;
try
{
PublishToCustomPublisher(originalException, additionalInfo, current);
}
catch (Exception publisherException)
{
/* Both of these calls use the DefaultPublisher which is the Application Log */
PublishInternalException(publisherException, null);
PublishToDefaultPublisher(originalException, additionalInfo);
}
You may also want to check out the newer Enterprise Library Exception Handling Application Block

Categories

Resources