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?
Converting C++ Builder code to C# .NET (TComponent, TOjbect, TList, etc.)
How to create a BMP file from raw byte in Java
Does SQL Server Compact Edition depend on the .net framework?
Moreover, there are different opinions under C++ programmers whether to use exceptions at all..
Is there a Java equivalent or methodology for the typedef keyword in C++?
Therefore you will find different recommendations by different people: Some like to use exception types from the standard library, some libraries (e.g.
Getting commands from string input
Poco) use a custom exception hierarchy (derived from std::exception), and others don't use exceptions at all (e.g.
Is it possible to make both a managed and unmanaged versions of the same C++ assembly?
floating point precision
If you want to stick to the standard library, there exists a specialized exception type:
Ways to speed up build time? (C#/Unmanaged C++)
For the reference: Here is an overview of standard exception types defined (and documented) in
#include <stdexcept> // ...
exception logic_error domain_error invalid_argument length_error out_of_range runtime_error range_error overflow_error underflow_error
Most people derive their own exception types from std::exception..
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.
std::logic_error or std::runtime_error.
. In fact it will. But only for dynamic_cast<> on references.
It will throw .
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 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..
std::invalid_argumentfor illegal arguments..