我只是在学习抛出异常而且我编写了一个代码,但当我输入Error: too big
或Error:too large
时似乎无法打印10000
或100000
。如何修复它以便打印Error: too big
或Error:too large
。
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
int xxx;
cout<<"please enter xxx:";
cin>>xxx;
if (xxx==1)
cout<<"2";
else if (xxx==10)
cout<<"3";
else if (xxx==100)
cout<<"4";
else if (xxx==1000)
cout<<"5";
else if (xxx==10000)
throw "too big";
else if (xxx==100000)
throw "too large";
return 0;
}
答案 0 :(得分:1)
你似乎把异常归咎于异常。
但在其核心,异常非常简单。基本上,它只是意味着某些低级代码会创建一个对象(通过throw
),最终会出现在某些更高级别的代码中(通过catch
)。
如果没有catch
,则异常会保持&#34;掉落&#34;函数调用堆栈,它一直这样做,直到它'#34;脱落&#34; main
。
当发生这种情况时,会发生一系列特殊事件。您可以使用相对高级的技术配置行为,但初学者真正需要知道的是,不保证在这种情况下打印任何错误消息。如果您希望异常导致错误消息,那么您必须自己编写必要的代码。
调整原始示例,该代码可能如下所示:
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
try
{
int xxx;
cout<<"please enter xxx:";
cin>>xxx;
if (xxx==1)
cout<<"2";
else if (xxx==10)
cout<<"3";
else if (xxx==100)
cout<<"4";
else if (xxx==1000)
cout<<"5";
else if (xxx==10000)
throw "too big";
else if (xxx==100000)
throw "too large";
return 0;
}
catch (char const* exc)
{
cerr << exc << "\n";
}
}
然而,更令人困惑的是,与大多数其他异常语言不同,C ++允许你抛出任何类型的对象。
让我们仔细看看这一行:
throw "too big";
"too big"
是char const[8]
类型的文字。 C ++允许你抛出这样的对象。因为它可以转换为char const*
到它的第一个元素,你甚至可以捕获它和其他大小的字符串文字char const*
。
但不常见。您应该抛出直接或间接从std::exception
派生的对象。
以下是使用<stdexcept>
标题中的标准类std::runtime_error
的示例。
(您的原始代码未使用<stdexcept>
中的任何内容。您可以在没有throw
的情况下完全使用<stdexcept>
。)
#include <iostream>
#include <stdexcept>
#include <exception>
int main()
{
try
{
int xxx;
std::cout << "please enter xxx:";
std::cin >> xxx;
if (xxx==1)
std::cout << "2";
else if (xxx==10)
std::cout << "3";
else if (xxx==100)
std::cout << "4";
else if (xxx==1000)
std::cout << "5";
else if (xxx==10000)
throw std::runtime_error("too big");
else if (xxx == 100000)
throw std::runtime_error("too large");
return 0;
}
catch (std::exception const& exc)
{
std::cerr << exc.what() << "\n";
}
}
答案 1 :(得分:-3)
throw必须只在try块中写入,所以写入try块中的所有条件并通过立即将它们移到try块之外来执行操作
try
{
condition
throw exception ;
}
catch exception
{
message or correction lines
}