在过去的 2 个小时里,我尝试了大约 20 次尝试并阅读了大量页面,但无法弄清楚我在这里做错了什么:
#pragma once
#include <exception>
using namespace std;
class EmptyHeap : public exception {
public:
virtual const char* what() const throw()
{
return "The heap is empty!";
}
};
然后在堆类中,一个公共(public)方法:
void remove() throw()//EmptyHeap
{
if (isEmpty())
{
EmptyHeap broken;
throw broken;
}
...
此代码有效,但原始标题为:
void remove() throw EmptyHeap;
有没有一种方法可以指定方法在 C++ 中抛出的异常,或者这只是 Java 的事情?
最佳答案
Is there a way to specify what exception a method throws in C++, or is that just a Java thing?
是的,是的,这是一个在任何 C++ 程序中都极不受欢迎的 Java 东西。如果函数可以抛出异常,则将异常说明留空。如果不能,请使用 noexcept
(>= c++11) 或 throw()
(< c++11)
此外,您可以通过从 std::runtime_error
或 std::logic_error
(或任何其他标准错误)派生任何用户异常来帮助自己).
例如
#include <stdexcept>
// this is literally all you need.
struct EmptyHeap : std::logic_error {
// inherit constructor with custom message
using logic_error::logic_error;
// provide default constructor
EmptyHeap() : logic_error("The heap is empty") {}
};
现在抛出:
throw EmptyHeap();
或使用自定义消息:
throw EmptyHeap("the heap is really empty");
关于C++ 指示类函数抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935491/