加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中创建新的异常

发布时间:2020-12-16 03:11:06 所属栏目:百科 来源:网络整理
导读:我有一个C类,我试图在Ubuntu中运行它: #ifndef WRONGPARAMETEREXCEPTION_H_#define WRONGPARAMETEREXCEPTION_H_#include iostream#include exception#include stringusing namespace std;#pragma onceclass WrongParameterException: public exception{ pub
我有一个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 Exceptions和exceptions article.

祝你好运!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读