自定义异常类——为什么我们需要它
Custom Exception Class - Why do we need it?
我正在阅读关于自定义异常…我就是这么做的。
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
class myBase : public exception
{
public:
myBase() {};
virtual ~myBase(void) {};
virtual const char* what() const { return "Hello, you have done a mistake"; }
};
class myDerived : public myBase
{
public:
myDerived() {};
virtual ~myDerived(void) {};
const char* what() const { return "Hello, you have done a mistake in - derived class"; }
};
int main(void)
{
try
{
throw myDerived();
}
catch (exception& e)
{
cout << e.what() << endl;
}
getchar();
return 0;
}
我明白了,我可以抛出我的自定义类对象,并且可以捕获它。我不明白你这么做的目的。有人能告诉我为什么我们需要自定义异常类吗?任何实际的例子都会帮助我理解使用自定义异常类的目的。
谢谢。
假设还有另一个用户定义的class
也继承自class myBase
:
class myDerived2 : public myBase {
public:
myDerived2() {}
virtual ~myDerived2() {}
};
假设你有一个try
catch
子句:
try {
myDerived A;
myDerived2 B;
...
/* to staff with both A and B */
...
} catch (std::exception& e){
cout << e.what() << endl;
}
在上面的
try - catch
子句中,您通过以相同的方式处理myDerived
和myDerived2
类型的异常来限制自己。如果您想以不同的方式处理
myDerived
和myDerived2
类型的抛出,该怎么办?那么你必须定义一个不同的
try-catch
子句:
try {
myDerived A;
myDerived2 B;
...
/* to staff with both A and B */
...
} catch (myDerived &d1) {
/* treat exception of type myDerived */
} catch (myDerived &d2) {
/* treat exception of type myDerived2 */
}
- 从上面的例子中,我认为很明显,定义自定义异常为程序员提供了一个有价值和通用的工具,以更通用和专门的方式处理抛出。
在c++中你可以抛出任何你想要的类型,你不需要从std::exception
继承。在不同的catch语句中捕获不同类型的能力很有用,因为您可以针对不同的条件抛出不同的异常类型。通过这种方式,您可以正确地处理不同的异常情况。
在这个简单的例子中,基于变量one
,在catch语句中抛出和处理一个不同的异常。在本例中,"string"被打印到stdout
。
#include <iostream>
using namespace std;
int main(void)
{
int one = 0;
try
{
if(one)
throw 1;
else
throw "string";
}
catch (int& i)
{
cout << i << endl;
}
catch (const char* s)
{
cout << s << endl;
}
return 0;
}
相关文章:
- C++ 中的自定义异常:在哪里定义它们?
- 我应该C++自定义异常代码放在哪里?
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 处理许多自定义异常的最佳方法是什么
- C++未显示自定义异常消息
- 自定义异常中的消息已损坏
- 为什么要创建自己的自定义异常类
- C++ 构造函数中的自定义异常抛出 ()
- JNI自定义异常具有多个参数
- 如何在抛出未处理的自定义异常后调用 what()?
- 无法创建两个从 std::logic_error 继承的自定义异常类
- 引发异常并直接结束程序的自定义异常处理
- 在C++中创建自定义异常
- G++ 自定义异常处理程序
- GNU C++:为什么自定义类不能是unordered_map的值类型
- 自定义异常并不总是执行 what()
- 从boost::exception和std::runtime_error继承自定义异常类
- 添加到方法的 C++ 自定义异常会出错
- 在自定义异常中仍可访问(误报?
- 自定义异常类——为什么我们需要它