在上一章中,我们了解了如何处理异常。在本章中,我们将看到如何定义自己的exeption。
在C ++中未预定义的情况下,用户定义的异常可能很有用。
在这种情况下,我们应该定义自己的例外。
我们可以通过继承异常类并重写其功能以适应我们的需求来创建自己的异常。
以下是有关如何创建用户定义的异常的示例。
示例1:简单的用户定义的异常
#include <iostream> #include <mutex> #include <thread> // for more tutorial in C ++ visit www.prodevelopertutorial.com using namespace std; class MyException : public exception { public: char * what () { return "Custom exception"; } }; int main() { try { throw MyException(); } catch(MyException e) { cout << "Custom exception has been caught" <<endl; cout << e.what() <<endl; } catch(exception e) { //Other errors } return 0; }
输出:
Custom exception has been caught Custom exception
引发用户定义的异常
#include <iostream> // std::cout // for more tutorials visit www.ProDeveloperTutorial.com using namespace std; class MyClass { }; int main() { try { throw MyClass(); } catch (MyClass myObj) { cout << "MyClass exception caught \n"; } }
输出:
MyClass exception caught