简体   繁体   中英

Throwing anonymous exception subclass

I was playing with c++ exceptions and I've tried throwing an anonymous exception like this:

throw class : public std::exception
{
    virtual const char *what() const noexcept
    {
        return "Custom exception";
    }
} ex;

However I'm getting the following error when trying to compile:

error: expected primary-expression before ‘class’
throw class : public std::exception
      ^

My compiler is gcc 5.2.1 on Linux x86_64.

How can I achieve the desired result?

This is not an answer per-se, but some important information what will help you going forward:

First, throwing an anonymous exception is unlikely to be useful. Exceptions are caught by their type. If you can't name the type, you can't catch the exception explicitly - only by its base, in which case you may as well have just thrown the base.

Second (and this is important):

There's rarely a good reason to derive from std::exception directly. You should derive from one of the exception types defined in <stdexcept>

these are:

std::runtime_error - indicating that some runtime condition makes it impossible to perform the service at the moment (such as a missing file).

std::logic_error - indicating that what was attempted will never be possible and the program is fundamentally in error in a way that could not be detected at compile time.

Handy reference here:

http://en.cppreference.com/w/cpp/header/stdexcept

You can't declare a class in a throw statement. Declare the class first (anonymously if you like, naming it via a typedef) , then you can throw it.

Better is to name the exception class, but put it in the nameless namespace:

namespace {
   class LocalException : public std::exception {
       const char *what() const noexcept override {
           return "Custom exception";
       }
    };
 }
    ....
    throw LocalException();

or, if you insist, you can create an object of anonymous class, and throw that.

static class : public std::exception {
   const char *what() const noexcept override {
       return "Custom exception";
   }
 } LocalExceptionObject;
    ....
    throw LocalExceptionObject;

Edit If you create a typedef, somebody can copy it, and it names the same class. You have to create an object of the anonymous class, and then nobody can name it.

Having said that, I don't think having anonymous things is useful. Far better to declare the class in a nameless namespace (so you know it is private), and just use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM