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

    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
      • N N a v a n e e t h

        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 Offline
        G Offline
        George_George
        wrote on last edited by
        #52

        Thanks N a v a n e e t h, So, asynchronous function call is the only case when we can catch exception from another thread? regards, George

        N 1 Reply Last reply
        0
        • G George_George

          Thanks Derek, Cool!! Your 1st link is Java... :-) I am interested in your 2nd link. But confused what means "catching untestable errors" and "not controlling programming flow"? Could you show some samples please? regards, George

          D Offline
          D Offline
          Derek Bartram
          wrote on last edited by
          #53

          George_George wrote:

          But confused what means "catching untestable errors"

          //writer is a stream writer to a file.. try { writer.Write("Hello"); } catch (Exception err) { //handle error } In this case you couldn't test for every possible error as some are far out the scope of plausible; e.g. can't access the file as it was on a removable drive that was just unplugged.

          George_George wrote:

          "not controlling programming flow"?

          //slider is a silder whos value is 0 to 100 double y = 100.0 / slider.Value then try { double y = 100.0 / slider.Value } catch (Exception) { //handler exception } is a bad way to write this code (remembing slider.Value could be 0 causing divide by 0 exception), a better way would be.... if (slider.Value != 0) { double y = 100.0 / slider.Value } else { handle error }

          G 1 Reply Last reply
          0
          • G George_George

            Thanks Derek, I agree with your exception handling approach. Any answers or comments to my original question? :-) regards, George

            D Offline
            D Offline
            Derek Bartram
            wrote on last edited by
            #54

            See above. I don't know the answer, but use the proceedure above will tell you how to find out.

            G 1 Reply Last reply
            0
            • D Derek Bartram

              George_George wrote:

              But confused what means "catching untestable errors"

              //writer is a stream writer to a file.. try { writer.Write("Hello"); } catch (Exception err) { //handle error } In this case you couldn't test for every possible error as some are far out the scope of plausible; e.g. can't access the file as it was on a removable drive that was just unplugged.

              George_George wrote:

              "not controlling programming flow"?

              //slider is a silder whos value is 0 to 100 double y = 100.0 / slider.Value then try { double y = 100.0 / slider.Value } catch (Exception) { //handler exception } is a bad way to write this code (remembing slider.Value could be 0 causing divide by 0 exception), a better way would be.... if (slider.Value != 0) { double y = 100.0 / slider.Value } else { handle error }

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

              Thanks Derek, I agree with your sample one. But for the sample two, I can not see any advantage for the 1st sample. Because for the 2nd you preferred sample, when we write code for "handle error" in else bracket, we usually throw exception. So, both samples have the same effect of exception thrown when we met with divide by zero issues. So, what do you think are the advantages?

              try
              {
              double y = 100.0 / slider.Value
              }
              catch (Exception)
              {
              //handler exception
              }

              is a bad way to write this code (remembing slider.Value could be 0 causing divide by 0 exception), a better way would be....

              if (slider.Value != 0)
              {
              double y = 100.0 / slider.Value
              }
              else
              {
              handle error
              }

              regards, George

              D 1 Reply Last reply
              0
              • D Derek Bartram

                See above. I don't know the answer, but use the proceedure above will tell you how to find out.

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

                Thanks Derek, "the proceedure above" you mean "catch (Exception err) and output err.GetType()"? regards, George

                D 1 Reply Last reply
                0
                • G George_George

                  Thanks Derek, "the proceedure above" you mean "catch (Exception err) and output err.GetType()"? regards, George

                  D Offline
                  D Offline
                  Derek Bartram
                  wrote on last edited by
                  #57

                  Yes. A breakpoint on the err.GetType() line will give you further information as well however.

                  G 1 Reply Last reply
                  0
                  • G George_George

                    Thanks Derek, I agree with your sample one. But for the sample two, I can not see any advantage for the 1st sample. Because for the 2nd you preferred sample, when we write code for "handle error" in else bracket, we usually throw exception. So, both samples have the same effect of exception thrown when we met with divide by zero issues. So, what do you think are the advantages?

                    try
                    {
                    double y = 100.0 / slider.Value
                    }
                    catch (Exception)
                    {
                    //handler exception
                    }

                    is a bad way to write this code (remembing slider.Value could be 0 causing divide by 0 exception), a better way would be....

                    if (slider.Value != 0)
                    {
                    double y = 100.0 / slider.Value
                    }
                    else
                    {
                    handle error
                    }

                    regards, George

                    D Offline
                    D Offline
                    Derek Bartram
                    wrote on last edited by
                    #58

                    The point is sample two doesn't throw an exception but rather just run a different section of code. An if statement inherinatly has less overhead than that of a try...catch statement. Certainly both will perform exactly the same function however the second will run more efficiently and quicker.

                    G 1 Reply Last reply
                    0
                    • D Derek Bartram

                      The point is sample two doesn't throw an exception but rather just run a different section of code. An if statement inherinatly has less overhead than that of a try...catch statement. Certainly both will perform exactly the same function however the second will run more efficiently and quicker.

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

                      Thanks for your clarification, Derek! It is clear now. :-) regards, George

                      1 Reply Last reply
                      0
                      • G George_George

                        Thanks Derek, What do you mean "didn't specify 'massive' which didn't help" and "relative to performing an if test to prevent the exception"? Could you show more description or some pseudo code about your approach please? regards, George

                        D Offline
                        D Offline
                        Derek Bartram
                        wrote on last edited by
                        #60

                        Firstly, from above //writer is a stream writer to a file.. try { writer.Write("Hello"); } catch (Exception err) { //handle error } In this case you couldn't test for every possible error as some are far out the scope of plausible; e.g. can't access the file as it was on a removable drive that was just unplugged. George_George wrote: "not controlling programming flow"? //slider is a silder whos value is 0 to 100 double y = 100.0 / slider.Value then try { double y = 100.0 / slider.Value } catch (Exception) { //handler exception } is a bad way to write this code (remembing slider.Value could be 0 causing divide by 0 exception), a better way would be.... if (slider.Value != 0) { double y = 100.0 / slider.Value } else { handle error }

                        George_George wrote:

                        What do you mean "didn't specify 'massive' which didn't help"

                        It's all very well saying massive improvement or whatever, but if you don't give some quantative value or referance, massive has no meaning (it could save 0.1ms which in terms of clock cycle is alot, but probably less significant to compared to a complex if statement).

                        G 1 Reply Last reply
                        0
                        • D Derek Bartram

                          Yes. A breakpoint on the err.GetType() line will give you further information as well however.

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

                          Thanks for your clarification, Derek! regards, George

                          1 Reply Last reply
                          0
                          • D Derek Bartram

                            Firstly, from above //writer is a stream writer to a file.. try { writer.Write("Hello"); } catch (Exception err) { //handle error } In this case you couldn't test for every possible error as some are far out the scope of plausible; e.g. can't access the file as it was on a removable drive that was just unplugged. George_George wrote: "not controlling programming flow"? //slider is a silder whos value is 0 to 100 double y = 100.0 / slider.Value then try { double y = 100.0 / slider.Value } catch (Exception) { //handler exception } is a bad way to write this code (remembing slider.Value could be 0 causing divide by 0 exception), a better way would be.... if (slider.Value != 0) { double y = 100.0 / slider.Value } else { handle error }

                            George_George wrote:

                            What do you mean "didn't specify 'massive' which didn't help"

                            It's all very well saying massive improvement or whatever, but if you don't give some quantative value or referance, massive has no meaning (it could save 0.1ms which in terms of clock cycle is alot, but probably less significant to compared to a complex if statement).

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

                            Thanks Derek, So, "massive improvement" you mean performance improvements? regards, George

                            D 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:


                              D Offline
                              D Offline
                              Derek Bartram
                              wrote on last edited by
                              #63

                              MidwestLimey wrote:

                              I once worked on a project where the Project Lead insisted on try catch blocks in every bloody method.

                              That sounds a little overkill, however generally I do use try...catch blocks in all my gui event handlers so that application is a little more useful when something does go wrong.

                              MidwestLimey wrote:

                              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.

                              Thank you for that, personally that is of great interest. I'm actually in the middle of writing a series of articles on language performance so hopefully i'll be able to give further insite on this. Many thanks, Derek Bartram

                              1 Reply Last reply
                              0
                              • G George_George

                                Thanks Derek, So, "massive improvement" you mean performance improvements? regards, George

                                D Offline
                                D Offline
                                Derek Bartram
                                wrote on last edited by
                                #64

                                Yes. Although perhaps also in terms of code style.

                                G 1 Reply Last reply
                                0
                                • G George_George

                                  Thanks N a v a n e e t h, So, asynchronous function call is the only case when we can catch exception from another thread? regards, George

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

                                  George_George wrote:

                                  So, asynchronous function call is the only case when we can catch exception from another thread?

                                  George, we are not able to catch exceptions happening on another thread. In this case also it's not happening. We are catching exception in the asynchronous method it self and keeping it for future use. When end method is called, this exception will be thrown out. Have a look at the following code

                                  Exception raisedException = null; // This is accessible in the whole class
                                  void BeginRead()
                                  {
                                  try{
                                  //Do some asynchronous process
                                  }
                                  cath(Exception ex){
                                  raisedException = ex;
                                  }
                                  }
                                  void EndRead()
                                  {
                                  // Do something to stop asynchronous processing. You will call WaitHandle.WaitOne() here.
                                  if(raisedException != null) throw raisedException; //We are throwing the exception occured

                                  // No exceptions. So return the result
                                  

                                  }

                                  In the above code, we have handled the exception and threw it when end is called. Note we handled the exception in the same thread where asynchronous method is executing, not in the main thread. Hope things are 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
                                  • D Derek Bartram

                                    Yes. Although perhaps also in terms of code style.

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

                                    Thanks Derek, It is clear now. Sorry for my bad English. :-) regards, George

                                    D 1 Reply Last reply
                                    0
                                    • G George_George

                                      Thanks Derek, It is clear now. Sorry for my bad English. :-) regards, George

                                      D Offline
                                      D Offline
                                      Derek Bartram
                                      wrote on last edited by
                                      #67

                                      No problem. Your english is VERY good, certainly better than my other languages :)

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

                                        George_George wrote:

                                        So, asynchronous function call is the only case when we can catch exception from another thread?

                                        George, we are not able to catch exceptions happening on another thread. In this case also it's not happening. We are catching exception in the asynchronous method it self and keeping it for future use. When end method is called, this exception will be thrown out. Have a look at the following code

                                        Exception raisedException = null; // This is accessible in the whole class
                                        void BeginRead()
                                        {
                                        try{
                                        //Do some asynchronous process
                                        }
                                        cath(Exception ex){
                                        raisedException = ex;
                                        }
                                        }
                                        void EndRead()
                                        {
                                        // Do something to stop asynchronous processing. You will call WaitHandle.WaitOne() here.
                                        if(raisedException != null) throw raisedException; //We are throwing the exception occured

                                        // No exceptions. So return the result
                                        

                                        }

                                        In the above code, we have handled the exception and threw it when end is called. Note we handled the exception in the same thread where asynchronous method is executing, not in the main thread. Hope things are 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
                                        #68

                                        Thanks N a v a n e e t h, I agree with all of your points, except this one,

                                        N a v a n e e t h wrote:

                                        Note we handled the exception in the same thread where asynchronous method is executing, not in the main thread.

                                        My point is we should handle it in main thread. Here is my code to prove. Any comments? (sorry the code is a little messy, I used it to test for multi-purpose in this discussion.)

                                        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();
                                        */

                                                // ThreadPool.QueueUserWorkItem(new WaitCallback(Test.Method2));
                                        
                                                
                                                Console.WriteLine("We will use a Delegate now");
                                                Method1Delegate dlg = new Method1Delegate(Method1);
                                                IAsyncResult handle = dlg.BeginInvoke(null, null);
                                                
                                                Thread.Sleep(1000);
                                        
                                                Console.WriteLine("Was the exception reported so far?");
                                        
                                                try
                                                {
                                                    Console.WriteLine("Let's call EndInvoke");
                                                    dlg.EndInvoke(handle);
                                                }
                                                catch (Exception ex)
                                                {
                                                    Console.WriteLine("Exception: {0}", ex.Message);
                                                }
                                                    
                                        
                                        
                                                Thread.Sleep(5000);
                                        
                                                Console.WriteLine("Survived exception");
                                        
                                                return;
                                        
                                        N 1 Reply Last reply
                                        0
                                        • D Derek Bartram

                                          No problem. Your english is VERY good, certainly better than my other languages :)

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

                                          Thanks for your patience to help me, Derek! :-) I think one of the most important things for developer is to be patience to learn new things. 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