未处理的异常,甚至在添加try-catch块之后?c++
Unhandled exception, even after adding try-catch block ? C++
try
{
bool numericname=false;
std::cout <<"nnEnter the Name of Customer: ";
std::getline(cin,Name);
std::cout<<"nEnter the Number of Customer: ";
std::cin>>Number;
std::string::iterator i=Name.begin();
while(i!=Name.end())
{
if(isdigit(*i))
{
numericname=true;
}
i++;
}
if(numericname)
{
throw "Name cannot be numeric.";
}
} catch(string message)
{
cout<<"nError Found: "<< message <<"nn";
}
为什么我得到未处理的异常错误?即使在我添加了catch块来捕获抛出的字符串消息之后?
"Name cannot be numeric."
不是std::string
,它是const char*
,所以您需要像这样捕获它:
try
{
throw "foo";
}
catch (const char* message)
{
std::cout << message;
}
要捕获"foo"作为std::string
,您需要像这样抛出/捕获它:
try
{
throw std::string("foo");
}
catch (std::string message)
{
std::cout << message;
}
您应该发送std::exception
,如throw std::logic_error("Name cannot be numeric")
然后你可以用多态捕获它,你的投掷的潜在类型将不再是一个问题:
try
{
throw std::logic_error("Name cannot be numeric");
// this can later be any type derived from std::exception
}
catch (std::exception& message)
{
std::cout << message.what();
}
相关文章:
- 编译器是否必须始终删除 try-catch 块(如果它被证明是非抛出的)
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 在大型应用程序的main上使用try-catch
- RapidXML 节点在 try catch 块中具有正确的值,但它在块外为 nullptr
- 提取 try-catch 时出现运行时错误
- std::unique_ptr 在 try-catch 块中未捕获取消引用异常
- 何时删除 try-catch 块中的指针
- 是否有理由大多数/所有 try-catch 示例只对 throw 语句使用 void 子函数
- 循环try..catch ..确保输入有效或使用控制语句
- 构造函数中的异常:init() 方法、指针、大型 try/catch 或
- C++ C2509 在讲师的定义中使用 try: - catch
- 为什么未达到的 try-catch 块会增加运行时时间
- 在 C++ 中使用 try-catch 进行删除 [] 或删除操作是否必要
- ex.nested try-catch中的什么()更改
- 为什么 c++ try-catch 块不能在 ubuntu 上与 g++ 一起使用?
- 格式化文件异常被 try catch 块忽略
- libpng错误不会被try/catch块捕获
- 这个分号在try/catch宏之后的效果是什么
- 未处理的异常,甚至在添加try-catch块之后?c++