我正在阅读有关自定义异常的信息。这就是我所做的。
#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 */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句