Thread: Why new(nothrow) type[length] is still throwing exception?

  1. #1
    Registered User srikrish85's Avatar
    Join Date
    Jun 2015
    Posts
    6

    Unhappy Why new(nothrow) type[length] is still throwing exception?

    Hi,
    Good day. Btw I am using g++-4.9 in linux mint and the following code
    Code:
    buff = new(nothrow) int[space_needed];
    if(buff==nullptr)
    {
           //My code to handle error
    }
    still throws std::bad_array_new_length. But if nothrow parameter is passed to new, the exception should not be thrown by new am I right? This is still weird.

    Thanks in advance.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    It does look weird to me, but I have never bothered with nothrow new. Why not just write:
    Code:
    try
    {
        buff = new int[space_needed];
    }
    catch (const std::bad_alloc& e)
    {
        // My code to handle error
    }
    std::bad_array_new_length is derived from std::bad_alloc, so the above would handle it too.

    Then again, why are you not using an existing container class?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User srikrish85's Avatar
    Join Date
    Jun 2015
    Posts
    6
    Hi,
    Thanks for the reply. Yeah I was just learning this new (nothrow) functionality. I always handle the respective exceptions and I love the STL vector and array classes.
    I was just meddling around. It seems weired when it throws exception. I think this has to do something with the g++ compiler. Anyways thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Throwing an exception in int main()
    By Programmer_P in forum C++ Programming
    Replies: 10
    Last Post: 04-04-2011, 01:06 PM
  2. Problem throwing exception from destructor (GCC 3.4.5)
    By Sebastiani in forum C++ Programming
    Replies: 12
    Last Post: 06-13-2010, 05:46 PM
  3. CRecordset::Open() is throwing an exception
    By cpjust in forum Windows Programming
    Replies: 1
    Last Post: 02-13-2008, 12:15 PM
  4. help, throwing exception from constructor
    By terracota in forum C++ Programming
    Replies: 5
    Last Post: 07-02-2004, 05:44 PM
  5. Deconstructor throwing exception
    By subdene in forum C++ Programming
    Replies: 13
    Last Post: 06-26-2004, 03:52 AM