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

                  M Offline
                  M Offline
                  Mike Dimmick
                  wrote on last edited by
                  #22

                  In Visual Basic, this error is known as On Error Resume Next. I'm trying to get rid of this in a product I'm maintaining.

                  Stability. What an interesting concept. -- Chris Maunder

                  R 1 Reply Last reply
                  0
                  • M Mike Dimmick

                    In Visual Basic, this error is known as On Error Resume Next. I'm trying to get rid of this in a product I'm maintaining.

                    Stability. What an interesting concept. -- Chris Maunder

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

                    Mike Dimmick wrote:

                    On Error Resume Next

                    Actually, it is not as bad as the catch all. catch all can have severe problems.


                    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

                    M 1 Reply Last reply
                    0
                    • R Rama Krishna Vavilala

                      Mike Dimmick wrote:

                      On Error Resume Next

                      Actually, it is not as bad as the catch all. catch all can have severe problems.


                      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

                      M Offline
                      M Offline
                      Mike Dimmick
                      wrote on last edited by
                      #24

                      We had On Error Resume Next in a method of a COM class which looked like this:

                      Public Sub FormatMessage(vtArgs() As Variant)
                      For i = 0 To UBound(vtArgs)
                      ' Do something
                      Next
                      End Sub

                      This was fine when called from a VB6 client, but in VB.NET it was possible to pass Nothing as the argument. Trying to do UBound(vtArgs) caused an error to be raised, but the next statement was the next call to UBound(vtArgs). Result: infinite loop. Hmm, maybe I should post that...

                      Stability. What an interesting concept. -- Chris Maunder

                      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