微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C中创建新的异常

我有一个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

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

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&)

有谁能告诉我我做错了什么?我尝试将消息变量更改为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());
}

解决方法

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

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

#include <stdexcept>
#include <string>

class WrongParameterException : public std::runtime_error {
public:
    WrongParameterException(const std::string& message) 
        : std::runtime_error(message) { };
};

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

祝你好运!

原文地址:https://www.jb51.cc/c/112291.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐