我有一个C++类,我试图在Ubuntu中运行它:
#ifndef WRONGPARAMETEREXCEPTION_H_
#define WRONGPARAMETEREXCEPTION_H_
#include <iostream>
#include <exception>
#include <string>
using namespace std;
#pragma once
class WrongParameterException: public exception
{
public:
WrongParameterException(char* message): exception(message) {};
virtual ~WrongParameterException() throw() {};
};
#endif
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,编译器给我这个错误:
WrongParameterException.h: In constructor ‘WrongParameterException::WrongParameterException(char*)’:
WrongParameterException.h:14: error: no matching function for call to ‘std::exception::exception(char*&)’
/usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception()
/usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&)
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?我尝试将消息变量更改为string或const string,const string&但它没有帮助.
以下是我如何使用我从main创建的新异常:
try
{
if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL))
{
throw WrongParameterException("Error in the config or commands file");
}
}
catch(WrongParameterException e)
{
log.addMsg(e.what());
}
Run Code Online (Sandbox Code Playgroud)
X-I*_*nce 19
首先,#pragma once是错误的方法,了解标题包括警卫.关于SO的相关问题解释了为什么使用#pragma once它是错误的方法.维基百科解释了如何使用包含守卫,它们具有相同的目的而没有任何缺点.
其次,您使用它不知道的参数调用std :: exception的构造函数,在本例中是指向字符数组的指针.
#include <stdexcept>
#include <string>
class WrongParameterException : public std::runtime_error {
public:
WrongParameterException(const std::string& message)
: std::runtime_error(message) { };
};
Run Code Online (Sandbox Code Playgroud)
可能是你想要的.有关异常的更多信息,请查看C++ FAQ Lite关于异常的文章和cplusplus.com 上的例外文章.
祝好运!
我的建议是:
std::runtime_error.正如上面的X-Istence所建议的那样.它在概念上是一个运行时错误,并且std::runtime_error构造函数也接受std::string描述发生的事件的as参数.catch(WrongParameterException const& e)
(注意const引用)而不是catch(WrongParameterException e),因为首先,异常在你的情况下通常是常量,并且,使用引用,你捕获任何子类,WrongParameterException以防你的代码进化得更精细的异常处理.std :: exception的构造函数不接受字符串参数.你试图给它一个,这是导致编译错误的原因.
您需要存储您的字符串,最好将其作为std :: string而不是原始指针进行处理,并从what()方法中返回它.