繁体   English   中英

处理许多自定义异常的最佳方法是什么?

[英]What is the best way to handle many custom exceptions [closed]

由于某些要求,在我的cpp库中,我需要添加许多自定义例外(几乎50个以上),因此我正在考虑编写如下的自定义例外,

 #include <iostream>
 #include <exception>

 using namespace std;

 class ScaleException: public exception
 {
   virtual const char* what() const throw()
   {
     return "My ScaleException happened";
   }
 };



 class NotExistException: public exception
 {
   virtual const char* what() const throw()
   {
     return "NotExistException";
   }
 };

 class StateException: public exception
 {
   virtual const char* what() const throw()
   {
     return "StateException";
   }
 };


 int main ()
 {


   try
   {
     throw ScaleException();
   }
   catch (exception& e)
   {
     cout << e.what() << endl;
   }
   return 0;
 }

但是我担心的是,我需要编写这么多的自定义异常类(我有近50种以上的不同种类的异常,因此我可能最终会写出这么多异常类),是否有任何方法可以在一个或几个类中定义全部,并且抛出异常将很容易且意义十足。

我应该拥有哪种设计?

您应该考虑两个选择:

  1. 具有单个异常类,并且具有接收特定于异常的数据的构造函数:

     namespace mylib { using exception_kind_t = unsigned; enum ExceptionKind : exception_kind_t { InvalidScale = 0, NonExistentResource = 1, Whatever = 2 }; class exception : public std::exception { public: static const char*[] messages = { "invalid scale", "non-existent resource", "whatever" }; exception(exception_kind_t kind) : kind_(kind) { } exception(const exception&) = default; exception(exception&&) = default; exception_kind_t kind() const { return kind_; } virtual const char* what() const throw() { return messages[kind_]; } protected: exception_kind_t kind_; }; } // namespace mylib 
  2. 使用模板参数区分异常类:

     namespace mylib { using exception_kind_t = unsigned; enum ExceptionKind : exception_kind_t { InvalidScale = 0, NonExistentResource = 1, Whatever = 2 }; template <exception_kind_t Kind> class exception : public std::exception { static const char*[] messages = { "invalid scale", "non-existent resource", "whatever" }; exception_kind_t kind() const { return Kind; } virtual const char* what() const throw() { return messages[Kind]; } }; } // namespace mylib 

PS-我已经测试了此代码,只是在此处进行了涂写,因此请专注于构想而不是细节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM