为什么我不能从我的抛出异常中打印出错误?
How come I don't can't print out error from my throw exception?
我只是在学习抛出异常,我写了一个代码,但当我输入10000
或100000
时,似乎无法打印出Error: too big
或Error:too large
。我如何修复它,以便它可以打印出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;
}
您似乎将太多的魔力归因于异常。
但从本质上讲,例外情况非常简单。基本上,这只是意味着一些低级代码创建了一个对象(通过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";
}
}
然而,更令人困惑的是,与大多数其他有例外的语言不同,C++允许抛出任何类型的对象。
让我们仔细看看这条线:
throw "too big";
CCD_ 11是类型为CCD_。C++允许您抛出这样一个对象。由于它可以转换为第一个元素的char const*
,因此您甚至可以捕获它并将其他大小的文字字符串作为char const*
。
但这不是常见的做法。您应该抛出直接或间接从std::exception
派生的对象。
这里是使用来自<stdexcept>
报头的标准类std::runtime_error
的示例。
(您的原始代码没有使用<stdexcept>
中的任何内容。您可以在没有<stdexcept>
的情况下完美地使用throw
本身。)
#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";
}
}
throw必须只写在try块中,所以将所有条件都写入try块,并通过立即在try框外捕获条件来执行操作
try
{
condition
throw exception ;
}
catch exception
{
message or correction lines
}
- 如何循环打印顶点结构
- 泛型函数反向打印任何矢量,编译器出错
- 打印 Map 的元素值时出错
- 为什么我在打印这个结构指针时出错
- 返回 char* 出错,打印好,返回不好(c++)
- 打印没有索引 cpp 的字符数组时出错
- 使用 std::transform 打印映射<字符串、矢量<字符串*时出错> >
- 在Qt中打印8字节整数时出错
- 打印BST遍历时出错-分段错误
- 使用OpenCV putText在图像上打印时出错
- 从对象打印二维矢量时出错
- Visual Studio在打印函数地址时出错
- 发送 std::矢量<size_t>数组到函数和打印时出错
- c++:尝试从链表中的第二个节点(虚拟节点)开始打印时出错
- 我的堆栈使用链表时出错.无法打印数字循环.(C++)
- 我的堆栈的打印代码出现分段错误,不知道我哪里出错了。
- 用c++读取和打印文本文件时出错
- 打印出在指向字符串的指针中获取的数据时出错
- 打印字符串的所有子字符串时出错
- 尝试打印对象列表的矢量时出错