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. Other Discussions
  3. Clever Code
  4. Do you think this is a bad idea or not( C++)

Do you think this is a bad idea or not( C++)

Scheduled Pinned Locked Moved Clever Code
c++debugginghelpquestion
24 Posts 11 Posters 30 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.
  • R Rama Krishna Vavilala

    void SomeFunction()
    {
    try
    {
    //Do all kind of stuff
    }
    catch(_com_error& e)
    {
    MessageBox(GetErrorDescription(e));
    }
    catch(...)
    {
    MessageBox("Unexpected error. Please contact our tech support");
    }
    }

    What modification will you suggest?


    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

    N Offline
    N Offline
    Nish Nishant
    wrote on last edited by
    #2

    Replace MessageBox with a TRACE perhaps?

    Regards, Nish


    Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
    Currently working on C++/CLI in Action for Manning Publications. Also visit the Ultimate Toolbox blog

    1 Reply Last reply
    0
    • R Rama Krishna Vavilala

      void SomeFunction()
      {
      try
      {
      //Do all kind of stuff
      }
      catch(_com_error& e)
      {
      MessageBox(GetErrorDescription(e));
      }
      catch(...)
      {
      MessageBox("Unexpected error. Please contact our tech support");
      }
      }

      What modification will you suggest?


      Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

      E Offline
      E Offline
      Elenesski
      wrote on last edited by
      #3

      Unless the exceptions are "expected" and have proper "handlers", I would throw the exception again to cause the app to fail or allow some external rountine to handle the exception. Throwing the exception again allows all the callers to free memory, locks, files, etc. as the application gracefully crashes. Without it, you have no clue what your operating state is. - Ian

      L S 2 Replies Last reply
      0
      • R Rama Krishna Vavilala

        void SomeFunction()
        {
        try
        {
        //Do all kind of stuff
        }
        catch(_com_error& e)
        {
        MessageBox(GetErrorDescription(e));
        }
        catch(...)
        {
        MessageBox("Unexpected error. Please contact our tech support");
        }
        }

        What modification will you suggest?


        Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

        J Offline
        J Offline
        Jun Du
        wrote on last edited by
        #4

        To add to what has been replied, I wouldn't put "Do all kind of stuff" in a try-catch block. Make discretion what are critical pieces and what should be put in.

        Best, Jun

        1 Reply Last reply
        0
        • R Rama Krishna Vavilala

          void SomeFunction()
          {
          try
          {
          //Do all kind of stuff
          }
          catch(_com_error& e)
          {
          MessageBox(GetErrorDescription(e));
          }
          catch(...)
          {
          MessageBox("Unexpected error. Please contact our tech support");
          }
          }

          What modification will you suggest?


          Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

          D Offline
          D Offline
          Dan McCormick
          wrote on last edited by
          #5

          In our code, if we do a general catch(...), we call a common unhandled exception handler that:

          • logs the class name & method name that detected the problem
          • displays a message box to the user that an unrecoverable error has occurred
          • attempts a graceful shutdown of the application

          We never try to continue because we have no idea how the application has been compromised. And should another unhandled exception occur while we are trying to clean up, we just give up and die immediately. [ Hmm... 'Unhandled Exception Handler' -- that just might qualify as an oxymoron! ]

          Be clear about the difference between your role as a programmer and as a tester. The tester in you must be suspicious, uncompromising, hostile, and compulsively obsessed with destroying, utterly destroying, the programmer's software. ----- Boris Beizer

          S 1 Reply Last reply
          0
          • E Elenesski

            Unless the exceptions are "expected" and have proper "handlers", I would throw the exception again to cause the app to fail or allow some external rountine to handle the exception. Throwing the exception again allows all the callers to free memory, locks, files, etc. as the application gracefully crashes. Without it, you have no clue what your operating state is. - Ian

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #6

            Mr Code Project wrote:

            , I would throw the exception again to cause the app to fail or allow some external rountine to handle the exception.

            What would be the point in catching the exception there if you are just gonna re-throw it? The exception would find its way up to the calling method regardless and if it has a try/catch block it would be caught by it. There is no point in catching exceptions deep in the core of your code if you are not going to do anything but re-throw it.

            =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

            S 1 Reply Last reply
            0
            • R Rama Krishna Vavilala

              void SomeFunction()
              {
              try
              {
              //Do all kind of stuff
              }
              catch(_com_error& e)
              {
              MessageBox(GetErrorDescription(e));
              }
              catch(...)
              {
              MessageBox("Unexpected error. Please contact our tech support");
              }
              }

              What modification will you suggest?


              Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

              S Offline
              S Offline
              Stephen Hewitt
              wrote on last edited by
              #7

              It depends, but in general it's a bad idea. If you're using MSVC 6 or a later version using the asynchronous exception handling model (see here[^]) it's an extremely bad idea as it will swallow non-C++ exceptions such as access violations and make debugging pointer and memory errors much harder. A general rule of exception handling is that you should only catch what you expect to be thrown. A catch (…) is a bad construct when rated using this rule as it’s like an admission that you don’t know which exceptions can be thrown. If you do use a catch all you should, in general, re-throw.

              Steve

              A J R 3 Replies Last reply
              0
              • D Dan McCormick

                In our code, if we do a general catch(...), we call a common unhandled exception handler that:

                • logs the class name & method name that detected the problem
                • displays a message box to the user that an unrecoverable error has occurred
                • attempts a graceful shutdown of the application

                We never try to continue because we have no idea how the application has been compromised. And should another unhandled exception occur while we are trying to clean up, we just give up and die immediately. [ Hmm... 'Unhandled Exception Handler' -- that just might qualify as an oxymoron! ]

                Be clear about the difference between your role as a programmer and as a tester. The tester in you must be suspicious, uncompromising, hostile, and compulsively obsessed with destroying, utterly destroying, the programmer's software. ----- Boris Beizer

                S Offline
                S Offline
                Stephen Hewitt
                wrote on last edited by
                #8

                If you're using MSVC 6 or a later version using the asynchronous exception handling model (see here[^]) this practice is a bad idea as it means, for one, Dr. Watson can't generate a crash report.

                Steve

                1 Reply Last reply
                0
                • L Lost User

                  Mr Code Project wrote:

                  , I would throw the exception again to cause the app to fail or allow some external rountine to handle the exception.

                  What would be the point in catching the exception there if you are just gonna re-throw it? The exception would find its way up to the calling method regardless and if it has a try/catch block it would be caught by it. There is no point in catching exceptions deep in the core of your code if you are not going to do anything but re-throw it.

                  =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                  S Offline
                  S Offline
                  Stephen Hewitt
                  wrote on last edited by
                  #9

                  A general rule of exception handling is that you should only catch what you expect to be thrown. Making an application artificially robust does no one any good. For example, say we’ve got a doubly linked list and an exception (not expected) is thrown when we’re setting up the links for a new node. If we have a catch (…) handler like in the OP then the application will survive with a corrupted linked list structure and instead of an unhandled exception pointing the debugger at the exact problem line as soon as it occurs we’ll have a bizarre error far removed from the actual cause at some later point in time. catch (…) is dangerous if used incorrectly. About the only time it’s OK to use a catch (…) is when you re-throw. The point is that it allows the code to perform some cleanup (so we don’t leak resources) for an exception that isn’t handled locally but is further down the call stack. This is standard (and good) practice.

                  Steve

                  L 1 Reply Last reply
                  0
                  • E Elenesski

                    Unless the exceptions are "expected" and have proper "handlers", I would throw the exception again to cause the app to fail or allow some external rountine to handle the exception. Throwing the exception again allows all the callers to free memory, locks, files, etc. as the application gracefully crashes. Without it, you have no clue what your operating state is. - Ian

                    S Offline
                    S Offline
                    Stephen Hewitt
                    wrote on last edited by
                    #10

                    You get a 5 from me. Having seen first hand the havoc that catch alls can cause I can see the wisdom in this.

                    Steve

                    1 Reply Last reply
                    0
                    • S Stephen Hewitt

                      It depends, but in general it's a bad idea. If you're using MSVC 6 or a later version using the asynchronous exception handling model (see here[^]) it's an extremely bad idea as it will swallow non-C++ exceptions such as access violations and make debugging pointer and memory errors much harder. A general rule of exception handling is that you should only catch what you expect to be thrown. A catch (…) is a bad construct when rated using this rule as it’s like an admission that you don’t know which exceptions can be thrown. If you do use a catch all you should, in general, re-throw.

                      Steve

                      A Offline
                      A Offline
                      anu v k
                      wrote on last edited by
                      #11

                      In windows, an SEH __try{} __except() will do more good than a catch(...). You get to know more details , about the reason for the exception in this case.

                      S 1 Reply Last reply
                      0
                      • A anu v k

                        In windows, an SEH __try{} __except() will do more good than a catch(...). You get to know more details , about the reason for the exception in this case.

                        S Offline
                        S Offline
                        Stephen Hewitt
                        wrote on last edited by
                        #12

                        In C++ SEH __try{} __except(), if used incorrectly, can be even more troublesome. For one it doesn't destruct local objects as the stack is being unwound. On top of this all my previous points apply; handling an exception that isn't expected and just ploughing on is a bad idea regardless of the exception handling mechanism used.

                        Steve

                        1 Reply Last reply
                        0
                        • S Stephen Hewitt

                          A general rule of exception handling is that you should only catch what you expect to be thrown. Making an application artificially robust does no one any good. For example, say we’ve got a doubly linked list and an exception (not expected) is thrown when we’re setting up the links for a new node. If we have a catch (…) handler like in the OP then the application will survive with a corrupted linked list structure and instead of an unhandled exception pointing the debugger at the exact problem line as soon as it occurs we’ll have a bizarre error far removed from the actual cause at some later point in time. catch (…) is dangerous if used incorrectly. About the only time it’s OK to use a catch (…) is when you re-throw. The point is that it allows the code to perform some cleanup (so we don’t leak resources) for an exception that isn’t handled locally but is further down the call stack. This is standard (and good) practice.

                          Steve

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #13

                          I don't have a lot of experience in C++ but I have plenty in C#. I don't catch exceptions to just re-throw them. If I catch an exception in the lower level parts of my code I will actually do something and then re-throw if necessary. If an exception is thrown and it is caught up at the higher level I can just walk down the call stack to find the source and then add a try/catch block at the higher level code to catch that and do something. /////Low level code/// public DoStuff() { try { ... } catch(Exception ex) { throw ex;//whats the point? The higher level code will catch this regardless if this is here } } public DoStuff() { try { ... } catch(Exception ex) { ...// do stuff throw ex;//thats better } } ///end low level code///

                          =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                          S K 2 Replies Last reply
                          0
                          • L Lost User

                            I don't have a lot of experience in C++ but I have plenty in C#. I don't catch exceptions to just re-throw them. If I catch an exception in the lower level parts of my code I will actually do something and then re-throw if necessary. If an exception is thrown and it is caught up at the higher level I can just walk down the call stack to find the source and then add a try/catch block at the higher level code to catch that and do something. /////Low level code/// public DoStuff() { try { ... } catch(Exception ex) { throw ex;//whats the point? The higher level code will catch this regardless if this is here } } public DoStuff() { try { ... } catch(Exception ex) { ...// do stuff throw ex;//thats better } } ///end low level code///

                            =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                            S Offline
                            S Offline
                            Stephen Hewitt
                            wrote on last edited by
                            #14

                            The point is to handle local clean up. Here's an example in C++: HANDLE OpenTheFile(); void CloseTheFile(HANDLE hFile) void SeekToData(HANDLE hFile); int GetData(HANDLE hFile);   int GetDataFromFile() {     HANDLE hFile = OpenTheFile();     try     {        SeekToData(hFile);     }     catch (...)     {         CloseTheFile(hFile);         throw;     }       int val = GetData(hFile);     CloseTheFile(hFile);       return val; } In this case we use the catch (...) to perform local cleanup regardless of the error and re-throw the exception so other error handling, such as displaying an error, can be handled in another function (which called this function, directly of indirectly).

                            Steve

                            L 1 Reply Last reply
                            0
                            • S Stephen Hewitt

                              The point is to handle local clean up. Here's an example in C++: HANDLE OpenTheFile(); void CloseTheFile(HANDLE hFile) void SeekToData(HANDLE hFile); int GetData(HANDLE hFile);   int GetDataFromFile() {     HANDLE hFile = OpenTheFile();     try     {        SeekToData(hFile);     }     catch (...)     {         CloseTheFile(hFile);         throw;     }       int val = GetData(hFile);     CloseTheFile(hFile);       return val; } In this case we use the catch (...) to perform local cleanup regardless of the error and re-throw the exception so other error handling, such as displaying an error, can be handled in another function (which called this function, directly of indirectly).

                              Steve

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #15

                              Yes, thats what I was trying to say. My first response was because I thought the guy was saying you should re-throw exceptions even when you don't do anything in the catch block.

                              =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                              S 1 Reply Last reply
                              0
                              • L Lost User

                                Yes, thats what I was trying to say. My first response was because I thought the guy was saying you should re-throw exceptions even when you don't do anything in the catch block.

                                =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                                S Offline
                                S Offline
                                Stephen Hewitt
                                wrote on last edited by
                                #16

                                In general, the rules for catch (...) are like this:   - Don't have a catch (...) that does nothing or simply displays an error. This should be done in a catch block that catches a specific exception.   - If you have a catch (...) it should only perfom local cleanup and then re-throw the exception to a higher level.   - The last catch block that handles a specific exception should catch a specific type or the exception should be left unhandled and trigger an unhandled exception. Violating these rules results in fragile and hard to maintain code.

                                Steve

                                1 Reply Last reply
                                0
                                • S Stephen Hewitt

                                  It depends, but in general it's a bad idea. If you're using MSVC 6 or a later version using the asynchronous exception handling model (see here[^]) it's an extremely bad idea as it will swallow non-C++ exceptions such as access violations and make debugging pointer and memory errors much harder. A general rule of exception handling is that you should only catch what you expect to be thrown. A catch (…) is a bad construct when rated using this rule as it’s like an admission that you don’t know which exceptions can be thrown. If you do use a catch all you should, in general, re-throw.

                                  Steve

                                  J Offline
                                  J Offline
                                  Jorgen Sigvardsson
                                  wrote on last edited by
                                  #17

                                  Stephen Hewitt wrote:

                                  it's an extremely bad idea as it will swallow non-C++ exceptions such as access violations and make debugging pointer and memory errors much harder.

                                  I second that. It's a PITA for sure. :sigh:

                                  -- Mit viel Oktan und frei von Blei, eine Kraftstoff wie Benziiiiiiin!

                                  1 Reply Last reply
                                  0
                                  • L Lost User

                                    I don't have a lot of experience in C++ but I have plenty in C#. I don't catch exceptions to just re-throw them. If I catch an exception in the lower level parts of my code I will actually do something and then re-throw if necessary. If an exception is thrown and it is caught up at the higher level I can just walk down the call stack to find the source and then add a try/catch block at the higher level code to catch that and do something. /////Low level code/// public DoStuff() { try { ... } catch(Exception ex) { throw ex;//whats the point? The higher level code will catch this regardless if this is here } } public DoStuff() { try { ... } catch(Exception ex) { ...// do stuff throw ex;//thats better } } ///end low level code///

                                    =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                                    K Offline
                                    K Offline
                                    Kevin McFarlane
                                    wrote on last edited by
                                    #18

                                    Henize wrote:

                                    catch(Exception ex) { ...// do stuff throw ex;//thats better }

                                    This should be: catch(Exception ex) { ...// do stuff throw;//thats better } i.e., throw rather than throw ex otherwise you lose some of the stack trace.

                                    Kevin

                                    L 1 Reply Last reply
                                    0
                                    • S Stephen Hewitt

                                      It depends, but in general it's a bad idea. If you're using MSVC 6 or a later version using the asynchronous exception handling model (see here[^]) it's an extremely bad idea as it will swallow non-C++ exceptions such as access violations and make debugging pointer and memory errors much harder. A general rule of exception handling is that you should only catch what you expect to be thrown. A catch (…) is a bad construct when rated using this rule as it’s like an admission that you don’t know which exceptions can be thrown. If you do use a catch all you should, in general, re-throw.

                                      Steve

                                      R Offline
                                      R Offline
                                      Rama Krishna Vavilala
                                      wrote on last edited by
                                      #19

                                      Exactly. I was expecting this answer. Many programmer get excited that their program continues to run inspite of an exception like access violation and forget that there might be something dangerous that occured like memory overwrite etc. so the program may not be in a valid state to continue. I had tough time convincing one of the programmer to drop that habit.


                                      Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

                                      S M 2 Replies Last reply
                                      0
                                      • K Kevin McFarlane

                                        Henize wrote:

                                        catch(Exception ex) { ...// do stuff throw ex;//thats better }

                                        This should be: catch(Exception ex) { ...// do stuff throw;//thats better } i.e., throw rather than throw ex otherwise you lose some of the stack trace.

                                        Kevin

                                        L Offline
                                        L Offline
                                        Lost User
                                        wrote on last edited by
                                        #20

                                        Yeah. I forget about that sometimes:doh:

                                        =====Brain melting code===== static int Sqrt(int x){ if (x<0) throw new ArgumentOutOfRangeException(); int temp, y=0, b=0x8000, bshft=15, v=x; do { if (v>=(temp=(y<<1)+b<>=1)>0); return y; :omg: ====TSI TLFL EEOOLHTG===== ^^^^^^^^^^^^^^^^^ Decode that and you will win.;P ============Hint=========== cout << "33 20 57 4F 52 44 53 62 63 6B 77 6F 72 64 73";

                                        1 Reply Last reply
                                        0
                                        • R Rama Krishna Vavilala

                                          Exactly. I was expecting this answer. Many programmer get excited that their program continues to run inspite of an exception like access violation and forget that there might be something dangerous that occured like memory overwrite etc. so the program may not be in a valid state to continue. I had tough time convincing one of the programmer to drop that habit.


                                          Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

                                          S Offline
                                          S Offline
                                          Stephen Hewitt
                                          wrote on last edited by
                                          #21

                                          I've had similar experiences. I've also had to debug code which had bugs caused by such code and in the worst case the problem took weeks to track down.

                                          Steve

                                          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