Getting compiler error in the below code which is throwing std::exception
in g++ 4.8.2 on linux.
Any suggestion why this error is coming will be very helpful.
#include <iostream>
#include <stdexcept>
void function()
{
std::exception e((char*)"mmmm");
throw e;
}
int main(int argc, const char* arg[]) {
try {
function();
}
catch(const std::exception& e) {
e.what();
}
return 0;
}
error:
$ g++ t.cpp
t.cpp: In function ‘void function()’:
t.cpp:6:33: error: no matching function for call to ‘std::exception::exception(char*)’
std::exception e((char*)"mmmm");
^
t.cpp:6:33: note: candidates are:
In file included from /usr/include/c++/4.8/ios:39:0,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from t.cpp:1:
/usr/include/c++/4.8/exception:63:5: note: std::exception::exception()
exception() _GLIBCXX_USE_NOEXCEPT { }
^
/usr/include/c++/4.8/exception:63:5: note: candidate expects 0 arguments, 1 provided
/usr/include/c++/4.8/exception:60:9: note: std::exception::exception(const std::exception&)
class exception
^
/usr/include/c++/4.8/exception:60:9: note: no known conversion for argument 1 from ‘char*’ to ‘const std::exception&’
EDIT 1
But code is compiling and working well in Visual Studio 2010 compiler.
_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception()
: _Mywhat(NULL), _Mydofree(false) { }
_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception(const char * const & _What)
: _Mywhat(NULL), _Mydofree(false)
{
_Copy_str(_What);
}
_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception(const char * const & _What, int)
: _Mywhat(_What), _Mydofree(false) { }
_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception(const exception& _That)
: _Mywhat(NULL), _Mydofree(false)
What the C++ standard says about this?
std::exception
does not have a constructor that takes a std::string or a char*. Maybe you'd like to use std::runtime_error
?
no matching function for call to ...
means that you are trying to call a function that doesn't exist. std::exception
has no constructor that takes a char*
, or anything that can be converted from a char*
. It only has a default constructor, and a copy constructor.
As already pointed out in other answers, the constructor for std::exception
takes no arguments.
Your code compiles in MSVC because
exception(const char* const &message)
exception(const char* const &message, int)
are Microsoft extension to the C++ Standard Library (see Remarks here exception Class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With