在c++中使用异常
Using exception in g++
在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*
转换而来的构造函数。它只有一个默认构造函数和一个复制构造函数。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常