Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a literal assignment to int in C++ throw an exception?

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.]

like image 463
xuinkrbin. Avatar asked May 16 '12 16:05

xuinkrbin.


People also ask

What is a string exception?

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.

What happens when you throw an exception C++?

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.


1 Answers

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.

like image 118
Jerry Coffin Avatar answered Oct 11 '22 12:10

Jerry Coffin