Equivalent of IllegalArgumentException of Java in C++
-
22-08-2019 - |
Question
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?
Solution
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
OTHER TIPS
std::domain_error may be what you are looking for, but I suspect very few people use it. Most people derive their own exception types from std::exception.
I always use std::invalid_argument
for illegal arguments.
If by invalid you mean doesn't satisfied method expected values you can throw
std::logic_error
or
std::runtime_error.
If you mean something related to casts like one object can't be converted to another - there is no exception for that and it won't be thrown automatically.
In fact it will. But only for dynamic_cast<> on references. It will throw
std::bad_cast
I am not sure it is a good idea to throw this one by your own.
I prefer to use logic_error and its derivatives in case someone passed wrong parameter because it is a logic error: programmer passed wrong type of argument.
But more of all I like to use assert in such cases. Because such things like passing wrong values or types to your function can be acceptable only during development and such checks should be avoided in the release.
You can throw a standard exception or roll your own. You may want to include additional information in the exception you're throwing, and that would be a good reason to do your own.
Personally, I haven't seen such domain checking in systems I've worked on. It certainly isn't universal.