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 / C++ / MFC
  4. throw exception after allocating some memory [modified]

throw exception after allocating some memory [modified]

Scheduled Pinned Locked Moved C / C++ / MFC
performancehelptutorialquestion
13 Posts 6 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.
  • F Offline
    F Offline
    followait
    wrote on last edited by
    #1

    How to let the code be more elegant? Just too much delete. BTW, while not to deal the exception in side the function, try catch finally can't be used.

    void f()
    {
    char * buf = new char[128];
    ...
    if (...)
    {
    delete []buf;
    throw runtime_error("...");
    }
    ...
    if (...)
    {
    delete []buf;
    throw runtime_error("...");
    }
    }

    ===================== I think what I need is something like constructor and destructor, but for a function. By overriding operator() of a class may solve some problem, but the function it hard to be re-entrantable, and other misc problems. Most of the cases the function should be short, so this couldn't be a problem, but in some rare case, it has to deal a lot of data, and the function looks very long.

    modified on Friday, December 24, 2010 3:38 AM

    CPalliniC L J A 4 Replies Last reply
    0
    • F followait

      How to let the code be more elegant? Just too much delete. BTW, while not to deal the exception in side the function, try catch finally can't be used.

      void f()
      {
      char * buf = new char[128];
      ...
      if (...)
      {
      delete []buf;
      throw runtime_error("...");
      }
      ...
      if (...)
      {
      delete []buf;
      throw runtime_error("...");
      }
      }

      ===================== I think what I need is something like constructor and destructor, but for a function. By overriding operator() of a class may solve some problem, but the function it hard to be re-entrantable, and other misc problems. Most of the cases the function should be short, so this couldn't be a problem, but in some rare case, it has to deal a lot of data, and the function looks very long.

      modified on Friday, December 24, 2010 3:38 AM

      CPalliniC Offline
      CPalliniC Offline
      CPallini
      wrote on last edited by
      #2

      The try-catch block is the most elegant solution, why cannot you use it? Alternatives are the C-like goto and the if chain you depicted. :)

      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
      This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
      [My articles]

      In testa che avete, signor di Ceprano?

      F 1 Reply Last reply
      0
      • CPalliniC CPallini

        The try-catch block is the most elegant solution, why cannot you use it? Alternatives are the C-like goto and the if chain you depicted. :)

        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
        This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
        [My articles]

        F Offline
        F Offline
        followait
        wrote on last edited by
        #3

        I think exception is rarely happened, I want to catch it in the more outside fucntion, like main.

        CPalliniC 1 Reply Last reply
        0
        • F followait

          How to let the code be more elegant? Just too much delete. BTW, while not to deal the exception in side the function, try catch finally can't be used.

          void f()
          {
          char * buf = new char[128];
          ...
          if (...)
          {
          delete []buf;
          throw runtime_error("...");
          }
          ...
          if (...)
          {
          delete []buf;
          throw runtime_error("...");
          }
          }

          ===================== I think what I need is something like constructor and destructor, but for a function. By overriding operator() of a class may solve some problem, but the function it hard to be re-entrantable, and other misc problems. Most of the cases the function should be short, so this couldn't be a problem, but in some rare case, it has to deal a lot of data, and the function looks very long.

          modified on Friday, December 24, 2010 3:38 AM

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

          How about this?

          struct Exception
          {
          char *text;
          void *data;
          }

          enum ERROR{NONE,...};

          void f()
          {
          char * buf = new char[128];

              ERROR e = NONE;
          ...
          if (...) e = ...
          if (...) e = ...
          if (...) e = ...
              if(NONE != e)
              {
                Exception exp;
                exp.text = FindTextForError(e);
                exp.data = buf;
                throw exp;
              }
          

          }

          caller()
          {
          try
          {
          f()
          }
          catch(Exception exp)
          {
          delete exp.data;
          }
          }

          ...byte till it megahertz... my donation to web rubbish

          1 Reply Last reply
          0
          • F followait

            How to let the code be more elegant? Just too much delete. BTW, while not to deal the exception in side the function, try catch finally can't be used.

            void f()
            {
            char * buf = new char[128];
            ...
            if (...)
            {
            delete []buf;
            throw runtime_error("...");
            }
            ...
            if (...)
            {
            delete []buf;
            throw runtime_error("...");
            }
            }

            ===================== I think what I need is something like constructor and destructor, but for a function. By overriding operator() of a class may solve some problem, but the function it hard to be re-entrantable, and other misc problems. Most of the cases the function should be short, so this couldn't be a problem, but in some rare case, it has to deal a lot of data, and the function looks very long.

            modified on Friday, December 24, 2010 3:38 AM

            J Offline
            J Offline
            jk chan
            wrote on last edited by
            #5

            what abt using smarpointers(ref counting) ?

            If u can Dream... U can do it

            F 1 Reply Last reply
            0
            • F followait

              I think exception is rarely happened, I want to catch it in the more outside fucntion, like main.

              CPalliniC Offline
              CPalliniC Offline
              CPallini
              wrote on last edited by
              #6

              If you want to catch it in the main block, then why don't you just throw it? :)

              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
              [My articles]

              In testa che avete, signor di Ceprano?

              1 Reply Last reply
              0
              • F followait

                How to let the code be more elegant? Just too much delete. BTW, while not to deal the exception in side the function, try catch finally can't be used.

                void f()
                {
                char * buf = new char[128];
                ...
                if (...)
                {
                delete []buf;
                throw runtime_error("...");
                }
                ...
                if (...)
                {
                delete []buf;
                throw runtime_error("...");
                }
                }

                ===================== I think what I need is something like constructor and destructor, but for a function. By overriding operator() of a class may solve some problem, but the function it hard to be re-entrantable, and other misc problems. Most of the cases the function should be short, so this couldn't be a problem, but in some rare case, it has to deal a lot of data, and the function looks very long.

                modified on Friday, December 24, 2010 3:38 AM

                A Offline
                A Offline
                Aescleal
                wrote on last edited by
                #7

                If you don't want to use delete all over the place, don't manually manage memory. While it's a bit hard to see the context from the pared down code you've posted why not use an automatic array of char or use std::vector<char>? Then you won't have to worry about clearing up dynamically allocated memory as you won't be using any. Cheers, Ash

                F 1 Reply Last reply
                0
                • J jk chan

                  what abt using smarpointers(ref counting) ?

                  If u can Dream... U can do it

                  F Offline
                  F Offline
                  followait
                  wrote on last edited by
                  #8

                  Yes, it is fine. But when I manapulate a dababase instead of memory, for example, a prepared statement, I need to close it before leave. Hope it can be common.

                  E J 2 Replies Last reply
                  0
                  • A Aescleal

                    If you don't want to use delete all over the place, don't manually manage memory. While it's a bit hard to see the context from the pared down code you've posted why not use an automatic array of char or use std::vector<char>? Then you won't have to worry about clearing up dynamically allocated memory as you won't be using any. Cheers, Ash

                    F Offline
                    F Offline
                    followait
                    wrote on last edited by
                    #9

                    But when I manapulate a dababase instead of memory, for example, a prepared statement, I need to close it before leave. Hope it can be common.

                    1 Reply Last reply
                    0
                    • F followait

                      Yes, it is fine. But when I manapulate a dababase instead of memory, for example, a prepared statement, I need to close it before leave. Hope it can be common.

                      E Offline
                      E Offline
                      Eugen Podsypalnikov
                      wrote on last edited by
                      #10

                      Just define your statement as a class, that will perform all needed clearances and closing in its destructor. Then - declare an instance (not an allocation by new) of the class object in the throwing function - the destructor will be called in any case (for all on-stack-instances) :)

                      They sought it with thimbles, they sought it with care; They pursued it with forks and hope; They threatened its life with a railway-share; They charmed it with smiles and soap. :)

                      F 1 Reply Last reply
                      0
                      • E Eugen Podsypalnikov

                        Just define your statement as a class, that will perform all needed clearances and closing in its destructor. Then - declare an instance (not an allocation by new) of the class object in the throwing function - the destructor will be called in any case (for all on-stack-instances) :)

                        They sought it with thimbles, they sought it with care; They pursued it with forks and hope; They threatened its life with a railway-share; They charmed it with smiles and soap. :)

                        F Offline
                        F Offline
                        followait
                        wrote on last edited by
                        #11

                        A class is ok in the case. But in another case, the life scope of the object of the class may larger than the try..catch... block, this can bring problems, just because the scopes are not inconsistent. However, there seems no proper way which is also efficient. BTW, is there any language that can provide some thing like constructor and distructor for a function?

                        E 1 Reply Last reply
                        0
                        • F followait

                          A class is ok in the case. But in another case, the life scope of the object of the class may larger than the try..catch... block, this can bring problems, just because the scopes are not inconsistent. However, there seems no proper way which is also efficient. BTW, is there any language that can provide some thing like constructor and distructor for a function?

                          E Offline
                          E Offline
                          Eugen Podsypalnikov
                          wrote on last edited by
                          #12

                          All of the variables local defined in a function, will be constructed on the stack at the beginning of the function and then destructed - at the end of the function (even there was a throwing) :) So you could provide a class for a function service, for example:

                          class CDBStatement;

                          class CDBStatementService // a pseudo-function-service :)
                          {
                          bool m_bOwner;
                          CDBStatement* m_pcStatement;

                          public:
                          CDBStatementService(CDBStatement* pcStatement, bool bOwner)
                          : m_pcStatement(pcStatement), m_bOwner(bOwner) {};

                          ~CDBStatementService() {
                          if (m_pcStatement) {
                          m_pcStatement->Close();
                          if (m_bOwner) {
                          delete m_pcStatement;
                          }
                          }
                          }
                          };

                          void TestThrowing()
                          {
                          CDBStatementService cDBStatementService(new CDBStatement(), true);

                          // here could be a throwing... :)
                          //..

                          } // the destructor of the service will be called, even there was a throwing

                          They sought it with thimbles, they sought it with care; They pursued it with forks and hope; They threatened its life with a railway-share; They charmed it with smiles and soap. :)

                          1 Reply Last reply
                          0
                          • F followait

                            Yes, it is fine. But when I manapulate a dababase instead of memory, for example, a prepared statement, I need to close it before leave. Hope it can be common.

                            J Offline
                            J Offline
                            jk chan
                            wrote on last edited by
                            #13

                            you said u need to close the database before u leave right ? so leave means , when the scope of that object goes away right ? so it must be possible to implement via const/dest . say for example when ur function first called the const of the object(declared inside the function) executes and when ur function terminates , the dest of the object executes. u can safely put things there right ?

                            If u can Dream... U can do it

                            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