在c++中使用异常

Using exception in g++

本文关键字:异常 c++      更新时间:2023-10-16

在linux上的g++ 4.8.2中获得编译器错误抛出std::exception。任何提示为什么会出现这个错误将是非常有帮助的。

#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;
}

错误:

$ 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&’

编辑1

但是代码正在编译并且在Visual Studio 2010编译器中运行良好。

_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)

c++标准对此有何规定?

std::exception没有接受std::string或char*类型的构造函数。也许你想用std::runtime_error

在其他答案中已经指出,std::exception的构造函数不接受参数。
你的代码在MSVC中编译,因为

exception(const char* const &message)
exception(const char* const &message, int)

是微软对c++标准库的扩展(参见此处的备注异常类)

no matching function for call to ...意味着您正在尝试调用一个不存在的函数。std::exception没有接受char*或任何可以从char*转换而来的构造函数。它只有一个默认构造函数和一个复制构造函数。