ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

CPP第48章:CPP中的用户定义异常

前开发者教程 2020年2月26日
在上一章中,我们了解了如何处理异常。在本章中,我们将看到如何定义自己的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

该网站上可用的教程列表:

C编程20+章C ++编程80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统编程20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的


  • <em id="RxmNYj3" class="R7pIrAL"><param id="FSjjdUR"><colgroup class="CXhqIIV"><canvas id="FA1mbjf"></canvas></colgroup></param></em>




    <output id="SdIH8Is"><article id="qzMoa73" class="qZOasjX"><output id="Gy1pqFN"></output></article></output>
    <dt id="DRpuQ7h"></dt>