Do C standard library functions which are included in C++ throw exception?

1.1k Views Asked by At

In the below code, author points that new operator function call might cause an exception so that this implementation is not exception safe because object state is already changed in the first line.

String &String::operator =( const char *str ) {
    // state is changed
    delete [] s_;                                        

    if( !str ) str = "";

    // exception might occur because of new operator
    s_ = strcpy( new char[ strlen(str)+1 ], str );

    return *this;
}

While reading, I wondered that do C library functions throw exception in C++ ? I know that there is no exception in C but since we are using C++ compiler, there might be exceptions.

So, can we consider c standard lib functions as exception safe function calls ?

Thank you.

Btw, for the record, right way (exception safe) to implement above function is below.

String &String::operator =( const char *str ) {
    if( !str ) str = "";
    char *tmp = strcpy( new char[ strlen(str)+1 ], str );
    delete [] s_;
    s_ = tmp;
    return *this;
}
3

There are 3 best solutions below

0
On BEST ANSWER

Generally speaking, the C++ standard does not modify any of the functions from the C standard, except to decree the identifiers should refer to actual functions rather than macros. Thus, functions from the C standard library cannot throw an exception in any circumstance there the C standard decrees what a function can do.

Loopholes that would allow exceptions include things like undefined behavior or callbacks (e.g. passing a comparator to qsort that throws an exception... although I'm not actually sure if that's allowed by the C++ standard). I don't think it particularly likely that library providers would spend any effort trying to add a feature of throwing exceptions in situations where there is undefined behavior.

7
On

No - just because you compile with a C++ compiler doesn't mean exceptions will get thrown. C does not support exceptions, so a C program cannot throw any sort of exception.

0
On

While reading, I wondered that do C library functions throw exception in C++ ?

Not if you use the functions correctly. How could they? That would completely break backward compatibility.

However, if you use them incorrectly, undefined behaviour occurs. And in that case, a compiler can do anything it wants, including the throwing of exceptions.

For example, take the following program which exhibits undefined behaviour according to the C++ language standard:

#include <iostream>
#include <string.h>

int main()
{
    try
    {
        strcpy(nullptr, nullptr);
    }
    catch (...)
    {
        std::cerr << "exception\n";
    }
}

Compile it with Visual C++ 2013 using Structured Exception Handling as follows:

cl /nologo /Za /EHa /W4 stackoverflow.cpp

Result of the program:

exception