Is it safe to assume that static_cast will never throw an exception?
For an int to Enum cast, an exception is not thrown even if it is invalid. Can I rely on this behavior? This following code works.
enum animal {
CAT = 1,
DOG = 2
};
int y = 10;
animal x = static_cast<animal>(y);
For this particular type of cast (integral to enumeration type), an exception might be thrown.
Note that since C++17 such conversion might in fact result in undefined behavior, which may include throwing an exception.
In other words, your particular usage of
static_castto get an enumerated value from an integer is fine until C++17 and always fine, if you make sure that the integer actually represents a valid enumerated value via some kind of input validation procedure.Sometimes the input validation procedure completely eliminates the need for a
static_cast, like so:Do consider using something like the above structure, for it requires no casts and gives you the opportunity to handle boundary cases correctly.