抛出类类型作为异常
throwing a class type as an exception
class error
{
int x;
int y;
public:
error() { }
error(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<x<<endl<<y;
}
};
main()
{
error e;
try{
cout<<"press any key to test exceptionn";
getch();
throw error(99,22);
}
catch(error e)
{
cout<<"nexception caught successfullyn";
e.display();
}
}
throw error(99,22)
,该语句如何将类对象抛出到catch块?如果我们写"throw e;",那么可以理解将抛出一个对象,但是"throw error();"将只调用该类的构造函数,那么这段代码是如何工作的呢?
总是可以通过调用构造函数来提供临时对象。
假设我有一个类Frac来存储有理数。它支持+、-、*和/等。
如果我要计算(1/3 + 9/4)我可以把它写成
Frac ans = Frac(1,3) + Frac(9,4);
从函数返回对象也是如此:
Frac Frac::one() {
return Frac(1, 1);
}
或者甚至抛出异常,正如你的用例:
throw std::logic_error("This is a call to logic_error's constructor");
另一个提示,你应该总是在c++中"按引用"捕获异常,像这样:
catch (error & e) { /*...*/ }
这样做的原因是得到正确的多态行为的情况下,你有子类重新实现虚函数在你的异常类
相关文章:
- 您应该在什么时候创建自己的异常类型
- 为什么标准不允许通过引用捕获不完整的异常类型?
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 提出异常并处理C 的某些异常类型的正确方法是什么?
- 无法在谷歌测试中检查异常类型
- QT创建者和MSVC-忽略调试时特定的异常类型
- 如何捕获除使用 GDB 的异常类型之外的所有异常类型
- 异常是否应具有标志/消息,或者每个错误应具有异常类型
- 如何在不同的上下文(例如线程)中保留原始异常类型信息
- std::rethrow_exception和抛出的异常类型
- 捕获派生异常类型在 Clang/MacOS X 上失败
- C++:检查是否在没有外部库的情况下抛出了某个异常类型
- 如何猜测 libpqxx C++库函数引发的异常类型
- 获取异常类型
- catch语句如何在没有反射的情况下识别异常类型
- 我们应该使用标准库中的异常类型吗?
- 为什么我的程序从异常中崩溃,即使我捕获了异常类型
- 如何在Mac上从c++程序中自动获取异常类型和消息
- close()抛出什么异常类型
- c++中无法捕获异常:无法识别异常类型