0

I came across a problem that is the AccessViolationException was unhandled after i run my program for about a day long.

(More information: I am using Visual Studio 2010)

However, it does not state where this exception occurs, there were two options given to me which is "ok" and "continue". When i pressed ok, nothing happened so i pressed continue and the program stops debugging.

When i tried to find a solution, i understand that i can implement HandleProcessCorruptedStateExceptions to fix this problem. However, i have no clue where to start.

Do i simply include the codes below only? And where do i include these code?

[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
public static int Main() 
{ 
   try
     {
       // Catch any exceptions leaking out of the program CallMainProgramLoop(); 
     }
   catch (Exception e) 
       // We could be catching anything here 
     {
         // The exception we caught could have been a program error
        // or something much more serious. Regardless, we know that
        // something is not right. We'll just output the exception 
       // and exit with an error. We won't try to do any work when
       // the program or process is in an unknown state!

        System.Console.WriteLine(e.Message); 
        return 1; 
     } 

  return 0; 

}

Alternatively, i can also do this legacyCorruptedStateExceptionsPolicy but it says that i should input the required statement in the config file. Where can i find the config file?

Appreciate all the replies!

Community
  • 1
  • 1
  • You said _"i run my program for about a day long"_ and then _"i pressed continue and the program stops debugging"_ - does it mean that you running you program within Visual Studio debugger for days? – vasily.sib May 13 '19 at 03:15
  • @vasily.sib Yes, i am currently doing a project for a company and it requires to run the program for days. But this exception caused it to stop so i was told to fix it. I am using Visual Studio 2010. – Han Angeline May 13 '19 at 03:30
  • Have a look at [this question](https://stackoverflow.com/questions/5762526/how-can-i-make-something-that-catches-all-unhandled-exceptions-in-a-winforms-a). Also, be aware that Visual Studio 2010 reached End-of-Life in 2015 (and will reach extended support end date in the next year). – vasily.sib May 13 '19 at 03:37
  • @vasily.sib thank you so much for helping. I understand that i must implement the code as stated in the other post but do i just create the function thats all? Do i have to call it somewhere in my code? I am so sorry for asking redundant question because the program is running again so i cannot amend the codes. I just want to clarify first and once the exception comes again, i can just straight away change it. – Han Angeline May 13 '19 at 03:44

1 Answers1

-1

The actual answer for you question is here and I really shouldn't answer it again, but I want to show you some code sample and I don't want to write it in comment :)

In one of my projects from time to time there was an unpredictable exception. To catch it I write this code in Program.cs:

[STAThread]
static void Main()
{
    // add UnhandledException handler
    AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}

private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
    // prepare message for user
    var message = "There was an unknown exception while running <app_name>!";
    var exception = e.ExceptionObject as Exception;

    if (exception != null)
    {
        // change message if there was actual exception
        message = $"There was an {exception.GetType().Name} exception while running <app_name>! {exception.Message}";
        // adding inner exceptions messages
        var innerException = exception.InnerException;
        while (innerException != null)
        {
            message += $"\r\n-> {innerException.GetType().Name}: {innerException.Message}";
            innerException = innerException.InnerException;
        }
#if DEBUG
        // add tracing info
        message += $"\r\n\r\n{GetStackTrace(exception)}";
#endif
    }
    if (e.IsTerminating) message += "\r\n\r\n<app_name> will be closed.";

    // showing message to the user
    MessageBox.Show(message, "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#if DEBUG
private static string GetStackTrace(Exception exception)
{
    var trace = new System.Diagnostics.StackTrace(exception, fNeedFileInfo: true);
    var frames = trace.GetFrames()
        .Select((f, i) => {
            var filename = f.GetFileName();
            var methodInfo = f.GetMethod();

            var frame = $"#{i} in the method {methodInfo.DeclaringType.FullName}.{methodInfo.Name}()";
            if (filename != null) frame += $" (source file: {System.IO.Path.GetFileName(filename)}@{f.GetFileLineNumber()}:{f.GetFileColumnNumber()})";

            return frame;
        });

    return $"Full stack trace ({trace.FrameCount} frames total):\r\n{string.Join("\r\n", frames)}";
}
#endif

Now, when unhandled exception occurring - there will be a message box, that shows full exception message (and inner exceptions messages). There was also a full stack trace for Debug build with method name, line number and source filename where exception occure.

About HandleProcessCorruptedStateExceptions

You mention a HandleProcessCorruptedStateExceptions attribute in your comment. The docs clearly says that you shouldn't use it unless you absolutely sure that you need it.

Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.

By default, the common language runtime (CLR) does not deliver these exceptions to managed code, and the try/catch blocks (and other exception-handling clauses) are not invoked for them. If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method whose exception-handling clauses you want to execute. The CLR delivers the corrupted process state exception to applicable exception clauses only in methods that have both the HandleProcessCorruptedStateExceptionsAttribute and SecurityCriticalAttribute attributes.

Corrupted process state means that some really catastrophic things happens and it safer for your app to die right now. If you are still not scared enough, here is the Main() method from the example above with the HandleProcessCorruptedStateExceptions attribute set:

[STAThread]
[HandleProcessCorruptedStateExceptions, SecurityCritical]
static void Main()
{
    try
    {
        // add UnhandledException handler
        // AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
        // * in this particular case is not quite useful to handle this exceptions,
        //   because you already wrap your entire application in a try/catch block

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    catch (Exception ex)
    {
        // handle it somehow
    }
}
vasily.sib
  • 3,871
  • 2
  • 23
  • 26
  • Thank you so much! I was asked by my manager to create a log file for tracking the error and you answer it before i do my research. Thank you so much will try it once my program start having error! – Han Angeline May 13 '19 at 05:10
  • When i tried to input your code into a new file, it shows error on these line message += $"\r\n-> {innerException.GetType().Name}: {innerException.Message}"; and message = $"There was an {exception.GetType().Name} exception while running ! {exception.Message}"; but when i tried removing $ it works. Is it alright to remove it? I am so sorry for asking these questions. – Han Angeline May 13 '19 at 05:17
  • I guess it's because VS 2010 can't handle string interpolation. Just replace it with normal `string.Format()`. – vasily.sib May 13 '19 at 05:18
  • One more question, so sorry. If i were to try implementing the codes i stated above the HandleProcessCorruptedStateExceptions. Where should i input these code? Inside the Form1.cs or Program.cs? – Han Angeline May 13 '19 at 06:26
  • Thank you so much for answering my question! Appreciate it. – Han Angeline May 13 '19 at 06:38
  • @HanAngeline check my update of this answer about `HandleProcessCorruptedStateExceptions` – vasily.sib May 14 '19 at 03:45
  • Thank you so much. I was asking too much as its a project for submission. Really appreicate it. Will update the outcome soon. Thank you once again – Han Angeline May 14 '19 at 23:05