CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1

    Exception in constructor

    Is it possible to throw exception from a constructor?

    class A
    {
    A()
    {
    //some code
    throw;


    }


    }

  2. #2
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: Exception in constructor


    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  3. #3
    Join Date
    Nov 2006
    Location
    Essen, Germany
    Posts
    1,344

    Re: Exception in constructor

    It´s possible and perfectly OK for a constructor to throw an exception. In a constructor you don´t have any other options to indicate failure because it does not return anything (OK, OK, you can set a global error flag, but no one really wants that).
    - Guido

  4. #4
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: Exception in constructor


    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  5. #5
    Join Date
    Oct 2005
    Location
    England
    Posts
    803

    Re: Exception in constructor

    Just remember to think carefully about memory management when you start throwing exceptions.
    Rich

    Visual Studio 2010 Professional | Windows 7 (x64)
    Ubuntu

  6. #6
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Exception in constructor

    holestary's link addresses your question by recommending that exceptions be thrown from a constructor to indicate failure. This article elaborates on Rich2189's advice: GotW #66: Constructor Failures.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  7. #7
    Join Date
    Oct 2005
    Location
    England
    Posts
    803

    Re: Exception in constructor

    Quote Originally Posted by laserlight View Post
    This article elaborates on Rich2189's advice: GotW #66: Constructor Failures.
    Awesome article! *Devours*.

    Quote Originally Posted by www.gotw.ca
    Moral #7: Prefer using "resource acquisition is initialization" to manage resources. Really, really, really. It will save you more headaches than you can probably imagine.
    This being the most important point I think; well following that advice will lead to the least amount of headaches.
    Rich

    Visual Studio 2010 Professional | Windows 7 (x64)
    Ubuntu

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured