我刚刚学习抛出异常,我编写了一段代码,但当我输入or时,我似乎无法打印出Error: too bigor 。我该如何修复它,以便它可以打印出来或.Error:too large10000100000Error: too bigError: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;
}
Run Code Online (Sandbox Code Playgroud)
您似乎将太多的魔力归因于异常。
但从本质上讲,异常非常简单。基本上,它只是意味着一些低级代码创建了一个对象(通过throw),该对象最终出现在一些高级代码(通过catch)中。
如果没有catch,则异常会继续“下降”到函数调用堆栈,并且一直这样做,直到它“下降” 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";
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这里更令人困惑的是,与大多数其他带有异常的语言不同,C++ 允许您抛出任何类型的对象。
让我们仔细看看这一行:
Run Code Online (Sandbox Code Playgroud)throw "too big";
"too big"是类型的文字char const[8]。C++ 允许你抛出这样的对象。由于它可以转换为char const*第一个元素的 a ,因此您甚至可以将它和其他大小的字符串文字捕获为char const*。
但这并不常见。相反,您应该抛出直接或间接从 派生的对象std::exception。
std::runtime_error这是使用标头中的标准类的示例<stdexcept>。
(您的原始代码没有使用 中的任何内容<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";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2260 次 |
| 最近记录: |