C++ 指示类函数抛出自定义异常

标签 c++ throw custom-exceptions

在过去的 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_errorstd::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/

相关文章:

javascript - 为什么添加 Javascript 窗口对象时 Vtable 链接会出现问题?

c++ - c++ try try catch的所有命中命中终止于C++ 11 14和17

c# - 关于 throw 和 assert 的困惑

c# - 使用自定义异常返回信息 C#

访问使用 OpenCV 的 C++ 共享库的 Java 程序

c++ - 如何将文本写入窗口?

objective-c - 在 Swift 中使用一个返回 Optional 或 Throw 的 Objective-C 函数

Java自定义异常无法正常工作

php - 在 PHP 中记录自定义异常的最佳实践

c++ - 如何在 C++ 中并排显示两个函数?