C++ 异常 - 抛出一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27179011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Exception - Throw a String
提问by Jimmy
I'm having a small issue with my code. For some reason , when i try to throw a string with the code below ,i get an error in visual studio.
我的代码有一个小问题。出于某种原因,当我尝试使用下面的代码抛出一个字符串时,我在 Visual Studio 中收到错误消息。
#include <string>
#include <iostream>
using namespace std;
int main()
{
char input;
cout << "\n\nWould you like to input? (y/n): ";
cin >> input;
input = tolower(input);
try
{
if (input != 'y')
{
throw ("exception ! error");
}
}
catch (string e)
{
cout << e << endl;
}
}
Error :
错误 :
回答by Mr.C64
Throwing a string is really a bad idea.
扔一根绳子真的是个坏主意。
Feel free to define a custom exception class, and have a string embedded inside (or just derive your custom exception class from std::runtime_error
, pass an error message to the constructor, and use the what()
method to get the error string at the catch-site), but do notthrow a string!
随意定义一个自定义异常类,并在其中嵌入一个字符串(或者只是从 派生自定义异常类std::runtime_error
,将错误消息传递给构造函数,并使用该what()
方法在捕获站点获取错误字符串),但是千万不能丢一个字符串!
回答by Syntactic Fructose
you are currently throwing a const char*
and not a std::string
, instead you should be throwing string("error")
您当前正在抛出 aconst char*
而不是 a std::string
,而是应该抛出string("error")
edit: the error is resolved with
编辑:错误已解决
throw string("exception ! error");