在 C++ 中创建新的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/577270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:02:28  来源:igfitidea点击:

Creating new exception in C++

c++linuxexceptionubuntu

提问by X-Istence

I have a C++ class and I am trying to run it in Ubuntu:

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

when I try to compile it, the compiler gives me this error:

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

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

Can anyone tell me what am I doing wrong? I tried changing the message variable to stringor const stringor const string&but it didn't help.

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

Here is how I use the new exception that I created from main:

以下是我如何使用从 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());
}

回答by X-Istence

First, #pragma onceis the wrong way to go about it, learn about header include guards. Related question on SOexplains why using #pragma onceis the wrong way to go about it. Wikipedia explains how to use include guardswhich serve the same purpose without any of the downsides.

首先,#pragma once是错误的方法,了解 header 包含守卫。SO 上的相关问题解释了为什么使用#pragma once是错误的方法。维基百科解释了如何使用具有相同目的而没有任何缺点的包含守卫

Second, you are calling the constructor of std::exception with a parameter it does not know, in this case a pointer to a character array.

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

#include <stdexcept>
#include <string>

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

Would probably be what you want. For more information on exceptions, check out C++ FAQ Lite article on Exceptionsand the exceptions articleat cplusplus.com.

可能会是你想要的。有关异常的更多信息,请查看关于异常的C++ FAQ Lite 文章和cplusplus.com异常文章

Good luck!

祝你好运!

回答by Timbo

std::exception does not have a constructor that takes any kind of string, only a virtual what() method that returns the exception description.

std::exception 没有接受任何类型字符串的构造函数,只有一个返回异常描述的虚拟 what() 方法。

You will have to store the string yourself and return it from there.

您必须自己存储字符串并从那里返回它。

回答by Diego Sevilla

My advice would be:

我的建议是:

  1. Inherit from std::runtime_error. As advised by X-Istence above. It is conceptually a runtime error, and also the std::runtime_errorconstructor accepts a std::stringas argument describing what happened.
  2. About your catching the exception. I'd use catch(WrongParameterException const& e) (note the const reference) instead of catch(WrongParameterException e), because first, the exception is normally constant in your case, and, also, using the reference, you catch any subclass of WrongParameterExceptionin case your code evolves with some more refined exception handling.
  1. 继承自std::runtime_error. 正如上面 X-Istence 所建议的那样。它在概念上是一个运行时错误,并且std::runtime_error构造函数接受一个std::string描述发生了什么的参数。
  2. 关于您捕获异常。我会使用catch(WrongParameterException const& e) (注意 const 引用)而不是catch(WrongParameterException e),因为首先,在您的情况下,异常通常是常量,而且,使用引用,您可以捕获任何子类,WrongParameterException以防您的代码随着一些更精细的异常处理而发展。

回答by unwind

std::exception's constructor doesn't take a string argument. You're trying to give it one, which is what causes the compile error.

std::exception 的构造函数不接受字符串参数。你试图给它一个,这就是导致编译错误的原因。

You need to store your string, which would be better to handle as a std::string rather than a raw pointer, and return it from the what()method.

您需要存储您的字符串,最好将其作为 std::string 而不是原始指针进行处理,并从what()方法中返回它。

回答by Skizz

Looking at the declaration of the exception class in MS VS2K5, the constructor you want is:

查看MS VS2K5中异常类的声明,你想要的构造函数是:

exception (const char *const&);

so try changing your constructor to:

所以尝试将您的构造函数更改为:

WrongParameterException (const char *const message)

and see if that helps. Otherwise, store the pointer in your own class and implement all the relevant methods.

看看这是否有帮助。否则,将指针存储在您自己的类中并实现所有相关方法。

回答by David Bo?jak

A simple solution is to design your exception diferently. Here is a simple example:

一个简单的解决方案是设计不同的异常。这是一个简单的例子:

class MyException : public Exception
{
public:
   MyException(CString strError) { m_strError = strError; }

   CString m_strError;
};

Then you can simply use your exception message as you please. This is because Exception does not have a contructor that excepts a String, so you have to stlre it on your own.

然后您可以随意使用您的异常消息。这是因为 Exception 没有除 String 之外的构造函数,因此您必须自己处理它。