Joseph Schmidt
Joseph Schmidt

Reputation: 127

C++ Indicate Class Function Throws Custom Exception

I've tried about 20 attempts & read numerous pages for the last 2 hours and can't figure out what I'm doing wrong here:

#pragma once
#include <exception>
using namespace std;

class EmptyHeap : public exception {
public:
    virtual const char* what() const throw()
    {
        return "The heap is empty!";
    }
};

Then in the heap class, a public method:

void remove() throw()//EmptyHeap
{
    if (isEmpty())
    {
        EmptyHeap broken;
        throw broken;
    }
    ...

This code works, but the original header was:

void remove() throw EmptyHeap;

Is there a way to specify what exception a method throws in C++, or is that just a Java thing?

Upvotes: 0

Views: 1745

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69864

Is there a way to specify what exception a method throws in C++, or is that just a Java thing?

Yes there is, and yes it's a java thing that's extremely unwelcome in any c++ program. If the function can throw an exception, just leave the exception specification blank. If it must not, use noexcept (>= c++11) or throw() (< c++11)

In addition, you can help yourself a lot by deriving any user exception from either std::runtime_error or std::logic_error (or any of the other standard errors).

e.g.

#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") {}
};

now throw with either:

throw EmptyHeap();

or with a custom message:

throw EmptyHeap("the heap is really empty");

Upvotes: 1

Related Questions