Equivalent of IllegalArgumentException of Java in C++

Srikanth picture Srikanth · Mar 25, 2009 · Viewed 14.2k times · Source

In Java if an input argument to a method is invalid, we can throw an IllegalArgumentException (which is of type RuntimeException). In C++, there is no notion of checked and unchecked exceptions. Is there a similar exception in standard C++ which can be used to indicate a runtime exception? Or is there a common style not in the standard but everyone follows in practice for a situation like this?

Or, should I just create my own custom exception and throw it?

Answer

Ferdinand Beyer picture Ferdinand Beyer · Mar 25, 2009

Unlike Java, C++ does not have a "standard framework" but only a small (and optional) standard library. Moreover, there are different opinions under C++ programmers whether to use exceptions at all.

Therefore you will find different recommendations by different people: Some like to use exception types from the standard library, some libraries (e.g. Poco) use a custom exception hierarchy (derived from std::exception), and others don't use exceptions at all (e.g. Qt).

If you want to stick to the standard library, there exists a specialized exception type: invalid_argument (extends logic_error).

#include <stdexcept>

// ...
throw std::invalid_argument("...");

For the reference: Here is an overview of standard exception types defined (and documented) in stdexcept:

exception
    logic_error
        domain_error
        invalid_argument
        length_error
        out_of_range
    runtime_error
        range_error
        overflow_error
        underflow_error