Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. uncaught exception handlers

uncaught exception handlers

Scheduled Pinned Locked Moved C#
tutorialquestionlearning
73 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Spacix One

    If you wanted to go that far you can catch errors in your thread method also... Are you looking for on error resume next type functionally? If so might be better to use VB.NET as C# doesn't allow for that coding horror :) You need to remember the following: Using exceptions to control programming logic is is the same as having car insurance to repair the damange after rolling off a cliff instead of setting the parking break to prevent it from rolling away.


    -Spacix All your skynet questions[^] belong to solved

    G Offline
    G Offline
    George_George
    wrote on last edited by
    #32

    Thanks Spacix, 1.

    Spacix One wrote:

    If you wanted to go that far you can catch errors in your thread method also...

    So, no means to catch exception from another thread, right? :-) 2.

    Spacix One wrote:

    on error resume next type functionally? If so might be better to use VB.NET as C# doesn't allow for that coding horror

    Sorry, I have no experience in VB. Could you say something alternative to describe your ideas please? I do not quite understand, especially what do you mean "on error resume next type functionally". :-) regards, George

    N S 2 Replies Last reply
    0
    • N N a v a n e e t h

      George_George wrote:

      "Also exceptions occurring in unmanaged resources won't be handled too"

      Yes. It won't be handled. Because it runs out of CLR.

      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

      G Offline
      G Offline
      George_George
      wrote on last edited by
      #33

      Thanks N a v a n e e t h, 1. Seems UnhandledException is the only approach to handle exception from other threads, and I have tried even ProcessExit does not work. Here is my code to test. Could you review whether my code and my points are correct? :-) 2. After the handler for UnhandledException is executed, process is always terminated?

      using System;
      using System.Threading;

      namespace DelegateThread
      {
      class Test
      {
      private static void Method2 (object input)
      {
      Console.WriteLine("Method1 is throwing exception");
      throw new ApplicationException("**** oops ****");
      }

          private static void Method1()
          {
              Console.WriteLine("Method1 is throwing exception");
              throw new ApplicationException("\*\*\*\* oops \*\*\*\*");
          }
      
          private static void Handler1 (object sender, EventArgs e)
          {
              Console.WriteLine ("I am here");
          }
      
          private static void Handler3(object sender, EventArgs e)
          {
              Console.WriteLine("I am here");
          }
      
          delegate void Method1Delegate();
      
          static void Main(string\[\] args)
          {
              Console.WriteLine("We first use a thread");
      
              AppDomain.CurrentDomain.ProcessExit += new EventHandler (Test.Handler1);
              AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(Test.Handler3);
              
              Thread aThread
                  = new Thread(new ThreadStart(Method1));
              aThread.Start();
              
      
      
              Thread.Sleep(5000);
      
              Console.WriteLine("Survived exception");
      
              return;
      
          } // main
      }
      

      }

      regards, George

      N 1 Reply Last reply
      0
      • P PIEBALDconsult

        Indeed, I always put a try/catch in the Main.

        G Offline
        G Offline
        George_George
        wrote on last edited by
        #34

        But you can never catch exception from other threads, PIEBALDconsult. :-) regards, George

        1 Reply Last reply
        0
        • M MidwestLimey

          Derek Bartram wrote:

          Does anyone know if a try...catch block affects the performance of the try block code? I know it has a performance hit on hitting the block, but I wonder if it has a continuing effect beyond that.

          I once worked on a project where the Project Lead insisted on try catch blocks in every bloody method. I did some performance testing and could determine definitive costs with the setup and teardown of the block, but was unable to measure any discernable difference to the code internally. However the code was entirely managed, perhaps wrapping unmanaged code has other implications.


          I'm largely language agnostic


          After a while they all bug me :doh:


          G Offline
          G Offline
          George_George
          wrote on last edited by
          #35

          What do you mean "unable to measure any discernable difference to the code internally"? regards, George

          M 1 Reply Last reply
          0
          • G George_George

            Thanks N a v a n e e t h, 1. Seems UnhandledException is the only approach to handle exception from other threads, and I have tried even ProcessExit does not work. Here is my code to test. Could you review whether my code and my points are correct? :-) 2. After the handler for UnhandledException is executed, process is always terminated?

            using System;
            using System.Threading;

            namespace DelegateThread
            {
            class Test
            {
            private static void Method2 (object input)
            {
            Console.WriteLine("Method1 is throwing exception");
            throw new ApplicationException("**** oops ****");
            }

                private static void Method1()
                {
                    Console.WriteLine("Method1 is throwing exception");
                    throw new ApplicationException("\*\*\*\* oops \*\*\*\*");
                }
            
                private static void Handler1 (object sender, EventArgs e)
                {
                    Console.WriteLine ("I am here");
                }
            
                private static void Handler3(object sender, EventArgs e)
                {
                    Console.WriteLine("I am here");
                }
            
                delegate void Method1Delegate();
            
                static void Main(string\[\] args)
                {
                    Console.WriteLine("We first use a thread");
            
                    AppDomain.CurrentDomain.ProcessExit += new EventHandler (Test.Handler1);
                    AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(Test.Handler3);
                    
                    Thread aThread
                        = new Thread(new ThreadStart(Method1));
                    aThread.Start();
                    
            
            
                    Thread.Sleep(5000);
            
                    Console.WriteLine("Survived exception");
            
                    return;
            
                } // main
            }
            

            }

            regards, George

            N Offline
            N Offline
            N a v a n e e t h
            wrote on last edited by
            #36

            George_George wrote:

            and I have tried even ProcessExit

            ProcessExist is not needed here

            George_George wrote:

            After the handler for UnhandledException is executed, process is always terminated?

            mm, look like you are still not clear. I will try to explain once more. AppDomain.UnhandledException is not an exception handler like catch. It's an event which will be fired before program exits due to uncaught error. After handler is executed, process will be terminated. This is a new behavior from .NET 2.0 onwards. In handler you can do necessary steps to log the error. You can't prevent application ending. In that handler you can show friendly messages to user and inform him that we are closing. Considering all these points in mind, your demo code is working as expected. Handler is getting executed and application is closing. You need to change the handler3() method like this.

            private static void Handler3(object sender, UnhandledExceptionEventArgs e)
            {
            Exception exceptionOccured = e.ExceptionObject as Exception;
            string errorMessage = exceptionOccured.Message;
            Console.WriteLine("I am here");
            }

            . In this you can see how exception occurred is retrieved from the event argument. You can log the exception message and application will be exited gracefully. .NET 1.1 behavior can be taken back by setting some flag value in application.config file. See this[^]. But I don't recommend that, as I don't know the pros/cons of that. Hope it's clear now.

            All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

            G 1 Reply Last reply
            0
            • G George_George

              Thanks Spacix, 1.

              Spacix One wrote:

              If you wanted to go that far you can catch errors in your thread method also...

              So, no means to catch exception from another thread, right? :-) 2.

              Spacix One wrote:

              on error resume next type functionally? If so might be better to use VB.NET as C# doesn't allow for that coding horror

              Sorry, I have no experience in VB. Could you say something alternative to describe your ideas please? I do not quite understand, especially what do you mean "on error resume next type functionally". :-) regards, George

              N Offline
              N Offline
              N a v a n e e t h
              wrote on last edited by
              #37

              George_George wrote:

              I do not quite understand, especially what do you mean "on error resume next type functionally".

              It's a VB syntax used to resume the processing on errors. If on error resume next is provided on the code, errors will be skipped. Keep it in mind, this is for VB/VB.NET and not for C#.

              All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

              G 1 Reply Last reply
              0
              • G George_George

                Thanks Spacix, 1.

                Spacix One wrote:

                If you wanted to go that far you can catch errors in your thread method also...

                So, no means to catch exception from another thread, right? :-) 2.

                Spacix One wrote:

                on error resume next type functionally? If so might be better to use VB.NET as C# doesn't allow for that coding horror

                Sorry, I have no experience in VB. Could you say something alternative to describe your ideas please? I do not quite understand, especially what do you mean "on error resume next type functionally". :-) regards, George

                S Offline
                S Offline
                Spacix One
                wrote on last edited by
                #38

                N a v a n e e t h answered #2 As for number one you can catch them in that thread, example:

                System.Threading.Thread mythread = new System.Threading.Thread
                (delegate()
                {
                try
                {
                throw new Exception("Oh no, my thread crashed!");
                }
                catch(Exception err)
                {
                File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\error.log",
                DateTime.Now.ToString() + Environment.NewLine + err.ToString() + Environment.NewLine + Environment.NewLine);
                }
                });
                mythread.Start();


                -Spacix All your skynet questions[^] belong to solved

                G 1 Reply Last reply
                0
                • N N a v a n e e t h

                  George_George wrote:

                  and I have tried even ProcessExit

                  ProcessExist is not needed here

                  George_George wrote:

                  After the handler for UnhandledException is executed, process is always terminated?

                  mm, look like you are still not clear. I will try to explain once more. AppDomain.UnhandledException is not an exception handler like catch. It's an event which will be fired before program exits due to uncaught error. After handler is executed, process will be terminated. This is a new behavior from .NET 2.0 onwards. In handler you can do necessary steps to log the error. You can't prevent application ending. In that handler you can show friendly messages to user and inform him that we are closing. Considering all these points in mind, your demo code is working as expected. Handler is getting executed and application is closing. You need to change the handler3() method like this.

                  private static void Handler3(object sender, UnhandledExceptionEventArgs e)
                  {
                  Exception exceptionOccured = e.ExceptionObject as Exception;
                  string errorMessage = exceptionOccured.Message;
                  Console.WriteLine("I am here");
                  }

                  . In this you can see how exception occurred is retrieved from the event argument. You can log the exception message and application will be exited gracefully. .NET 1.1 behavior can be taken back by setting some flag value in application.config file. See this[^]. But I don't recommend that, as I don't know the pros/cons of that. Hope it's clear now.

                  All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                  G Offline
                  G Offline
                  George_George
                  wrote on last edited by
                  #39

                  Thanks N a v a n e e t h, Cool! I have made further tests that, there is one exception case. When exception is from thread pool thread -- but in the situation of executing asynchronous method call, we can catch the exception (even if unhandled in the thread pool worker thread) in EndInvoke in main thread. So, here is a case when there is unhandled exception in another thread, we can still catch it and not make process terminated. :-) Any comments? regards, George

                  N 1 Reply Last reply
                  0
                  • N N a v a n e e t h

                    George_George wrote:

                    I do not quite understand, especially what do you mean "on error resume next type functionally".

                    It's a VB syntax used to resume the processing on errors. If on error resume next is provided on the code, errors will be skipped. Keep it in mind, this is for VB/VB.NET and not for C#.

                    All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                    G Offline
                    G Offline
                    George_George
                    wrote on last edited by
                    #40

                    Thanks for clarification, N a v a n e e t h! regards, George

                    1 Reply Last reply
                    0
                    • S Spacix One

                      N a v a n e e t h answered #2 As for number one you can catch them in that thread, example:

                      System.Threading.Thread mythread = new System.Threading.Thread
                      (delegate()
                      {
                      try
                      {
                      throw new Exception("Oh no, my thread crashed!");
                      }
                      catch(Exception err)
                      {
                      File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\error.log",
                      DateTime.Now.ToString() + Environment.NewLine + err.ToString() + Environment.NewLine + Environment.NewLine);
                      }
                      });
                      mythread.Start();


                      -Spacix All your skynet questions[^] belong to solved

                      G Offline
                      G Offline
                      George_George
                      wrote on last edited by
                      #41

                      Yes, Spacix! I agree with your code. I think the only case which we can catch exception other threads and prevent application process from termination is, http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2529071[^] Agree? Any comments? :-) regards, George

                      S 1 Reply Last reply
                      0
                      • G George_George

                        What do you mean "unable to measure any discernable difference to the code internally"? regards, George

                        M Offline
                        M Offline
                        MidwestLimey
                        wrote on last edited by
                        #42

                        I couldn't find a time difference for the execution of the same code block when wrapped in a try catch as opposed to not.


                        I'm largely language agnostic


                        After a while they all bug me :doh:


                        G 1 Reply Last reply
                        0
                        • M MidwestLimey

                          I couldn't find a time difference for the execution of the same code block when wrapped in a try catch as opposed to not.


                          I'm largely language agnostic


                          After a while they all bug me :doh:


                          G Offline
                          G Offline
                          George_George
                          wrote on last edited by
                          #43

                          Thanks MidwestLimey, So you mean the performance impact of exception handling is minor? regards, George

                          S M 2 Replies Last reply
                          0
                          • G George_George

                            Yes, Spacix! I agree with your code. I think the only case which we can catch exception other threads and prevent application process from termination is, http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2529071[^] Agree? Any comments? :-) regards, George

                            S Offline
                            S Offline
                            Spacix One
                            wrote on last edited by
                            #44

                            Mostly, it's hard to state this is the ONLY case. It matters on who owns the threads and other stuff. It's definitely ONE way :)


                            -Spacix All your skynet questions[^] belong to solved

                            G 1 Reply Last reply
                            0
                            • G George_George

                              Thanks MidwestLimey, So you mean the performance impact of exception handling is minor? regards, George

                              S Offline
                              S Offline
                              Spacix One
                              wrote on last edited by
                              #45

                              I think he means the use of the

                              try
                              {
                              }
                              catch...

                              WITHOUT an Exception being thrown has little to no effect on code. The problem is when Exceptions do occur it slows everything down. Though I think that is better than the WHOLE app crashing to a grinding halt and a .NET error message dialog showing then the Microsoft error reporting tool (if enabled) poping up. Though this has been stated many times in this thread, using exceptions to contol logic is VERY VERY bad code:

                              public static bool someMethod()
                              {
                              try
                              {
                              //code process
                              if(somthing wrong)
                              {
                              throw new Exception("Error!!");
                              }
                              }
                              catch(Exception err)
                              {
                              return false;
                              }
                              }

                              There are only a few exceptions(pun intended) to this rule and anytime I've seen something like the code as above wasn't needed...


                              -Spacix All your skynet questions[^] belong to solved

                              M G 2 Replies Last reply
                              0
                              • G George_George

                                Thanks MidwestLimey, So you mean the performance impact of exception handling is minor? regards, George

                                M Offline
                                M Offline
                                MidwestLimey
                                wrote on last edited by
                                #46

                                I mean the code within the block doesn't magically slow down, however establishing the try catch block and then tearing it down does use some cycles.


                                I'm largely language agnostic


                                After a while they all bug me :doh:


                                G 1 Reply Last reply
                                0
                                • S Spacix One

                                  I think he means the use of the

                                  try
                                  {
                                  }
                                  catch...

                                  WITHOUT an Exception being thrown has little to no effect on code. The problem is when Exceptions do occur it slows everything down. Though I think that is better than the WHOLE app crashing to a grinding halt and a .NET error message dialog showing then the Microsoft error reporting tool (if enabled) poping up. Though this has been stated many times in this thread, using exceptions to contol logic is VERY VERY bad code:

                                  public static bool someMethod()
                                  {
                                  try
                                  {
                                  //code process
                                  if(somthing wrong)
                                  {
                                  throw new Exception("Error!!");
                                  }
                                  }
                                  catch(Exception err)
                                  {
                                  return false;
                                  }
                                  }

                                  There are only a few exceptions(pun intended) to this rule and anytime I've seen something like the code as above wasn't needed...


                                  -Spacix All your skynet questions[^] belong to solved

                                  M Offline
                                  M Offline
                                  MidwestLimey
                                  wrote on last edited by
                                  #47

                                  Spacix One wrote:

                                  The problem is when Exceptions do occur it slows everything down. Though I think that is better than the WHOLE app crashing to a grinding halt and a .NET error message dialog showing then the Microsoft error reporting tool (if enabled) poping up.

                                  You mean you don't think users like that? :D


                                  I'm largely language agnostic


                                  After a while they all bug me :doh:


                                  1 Reply Last reply
                                  0
                                  • G George_George

                                    Thanks N a v a n e e t h, Cool! I have made further tests that, there is one exception case. When exception is from thread pool thread -- but in the situation of executing asynchronous method call, we can catch the exception (even if unhandled in the thread pool worker thread) in EndInvoke in main thread. So, here is a case when there is unhandled exception in another thread, we can still catch it and not make process terminated. :-) Any comments? regards, George

                                    N Offline
                                    N Offline
                                    N a v a n e e t h
                                    wrote on last edited by
                                    #48

                                    George_George wrote:

                                    but in the situation of executing asynchronous method call, we can catch the exception (even if unhandled in the thread pool worker thread) in EndInvoke in main thread.

                                    This how asynchronous methods works. It will handle exception safely and throws when end method is called.

                                    George_George wrote:

                                    when there is unhandled exception in another thread, we can still catch it and not make process terminated.

                                    You are always allowed to catch exceptions in the same thread. Cross-thread exception handling is only not possible. In this case also you are handling exceptions in the same thread, so there won't be any issues. Asynchronous method runs on a thread pool thread and handles exception inside that method and keep it until end is called. When end is called, it will check exception is null, if not null it will be thrown.

                                    All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                    G 1 Reply Last reply
                                    0
                                    • S Spacix One

                                      Mostly, it's hard to state this is the ONLY case. It matters on who owns the threads and other stuff. It's definitely ONE way :)


                                      -Spacix All your skynet questions[^] belong to solved

                                      G Offline
                                      G Offline
                                      George_George
                                      wrote on last edited by
                                      #49

                                      Could you show me another way to catch exception from another thread please? :-) regards, George

                                      1 Reply Last reply
                                      0
                                      • S Spacix One

                                        I think he means the use of the

                                        try
                                        {
                                        }
                                        catch...

                                        WITHOUT an Exception being thrown has little to no effect on code. The problem is when Exceptions do occur it slows everything down. Though I think that is better than the WHOLE app crashing to a grinding halt and a .NET error message dialog showing then the Microsoft error reporting tool (if enabled) poping up. Though this has been stated many times in this thread, using exceptions to contol logic is VERY VERY bad code:

                                        public static bool someMethod()
                                        {
                                        try
                                        {
                                        //code process
                                        if(somthing wrong)
                                        {
                                        throw new Exception("Error!!");
                                        }
                                        }
                                        catch(Exception err)
                                        {
                                        return false;
                                        }
                                        }

                                        There are only a few exceptions(pun intended) to this rule and anytime I've seen something like the code as above wasn't needed...


                                        -Spacix All your skynet questions[^] belong to solved

                                        G Offline
                                        G Offline
                                        George_George
                                        wrote on last edited by
                                        #50

                                        Thanks Spacix, What do you mean "using exceptions to contol logic"? We should never throw any exception when there is some logical errors during runtime? regards, George

                                        S 1 Reply Last reply
                                        0
                                        • M MidwestLimey

                                          I mean the code within the block doesn't magically slow down, however establishing the try catch block and then tearing it down does use some cycles.


                                          I'm largely language agnostic


                                          After a while they all bug me :doh:


                                          G Offline
                                          G Offline
                                          George_George
                                          wrote on last edited by
                                          #51

                                          Thanks for clarifying this, MidwestLimey! regards, George

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups