Given code like the following:
void f()
{
int i;
i = 0;
}
is it possible the system could throw an exception due to the simple assignment?
[Edit: For Those saying, "No an exception cannot occur," can You point Me in the direction of the part of the C++ standard which says this? I am having trouble finding it.]
The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.
When an exception occurs within the try block, control is transferred to the exception handler. If no exception is thrown, the code continues normally and the handlers are ignored. An exception in C++ is thrown by using the throw keyword from inside the try block.
Although you'd probably be hard put to find an assurance of it in the standard, a simple rule of thumb is that anything that's legitimate in C probably can't throw. [Edit: The closest I'm aware of to a direct statement to this effect is at §15/2, which says that:
Code that executes a throw-expression is said to “throw an exception;” [...]
Looking at that in reverse, code that does not execute a throw-expression does not throw an exception.]
Throwing is basically restricted to two possibilities: the first is invoking UB. The second is doing something unique to C++, such as assigning to a user-defined type which overloads operator =
, or using a new
expression.
Edit: As far as an assignment goes, there are quite a few ways it can throw. Obviously, throwing in the assignment operator itself would do it, but there are a fair number of others. Just for example, if the source type doesn't match the target type, you might get a conversion via a cast operator in the source or a constructor in the target -- either of which might throw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With