在C中创建新的异常

前端之家收集整理的这篇文章主要介绍了在C中创建新的异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个C类,我试图在Ubuntu中运行它:
  1. #ifndef WRONGPARAMETEREXCEPTION_H_
  2. #define WRONGPARAMETEREXCEPTION_H_
  3.  
  4. #include <iostream>
  5. #include <exception>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. #pragma once
  11.  
  12. class WrongParameterException: public exception
  13. {
  14. public:
  15. WrongParameterException(char* message): exception(message) {};
  16. virtual ~WrongParameterException() throw() {};
  17. };
  18.  
  19. #endif

当我尝试编译它,编译器给我这个错误

  1. WrongParameterException.h: In constructor WrongParameterException::WrongParameterException(char*)’:
  2. WrongParameterException.h:14: error: no matching function for call to std::exception::exception(char*&)’
  3. /usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception()
  4. /usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&)

有谁能告诉我我做错了什么?我尝试将消息变量更改为string或const string或const string&但它没有帮助.

这是我如何使用我从main创建的新异常:

  1. try
  2. {
  3. if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL))
  4. {
  5. throw WrongParameterException("Error in the config or commands file");
  6. }
  7. }
  8. catch(WrongParameterException e)
  9. {
  10. log.addMsg(e.what());
  11. }

解决方法

首先,#pragma一次是错误方法,了解标题包括守卫. Related question on SO解释了为什么使用#pragma一次是错误方法.维基百科解释如何使用 include guards服务于相同的目的而没有任何缺点.

其次,您使用不知道的参数调用std :: exception的构造函数,在这种情况下是指向字符数组的指针.

  1. #include <stdexcept>
  2. #include <string>
  3.  
  4. class WrongParameterException : public std::runtime_error {
  5. public:
  6. WrongParameterException(const std::string& message)
  7. : std::runtime_error(message) { };
  8. };

可能是你想要的有关例外的更多信息,请查看c00plus.com的C++ FAQ Lite article on Exceptionsexceptions article.

祝你好运!

猜你在找的C&C++相关文章