can floating point multiplication throw an exception in C++? - c++

Is this possible? I don't think it is, but I don't know if this is something the standard would say, or if it's implementation defined? I'm asking because I'm wondering whether it's safe or worth it to mark a constexpr function like this noexcept
EX:
constexpr double to_meters(double y) noexcept? {
return y * 10;
}
constexpr double x = to_meters(y); // Clang-Tidy warns about possible exception without noexcept

No, float point multiplication will normally not throw a C++ exception.
But think about this: How can clang-tidy possibly know whether to_meter will throw an exception? In C++ every function can throw an exception unless it is explicitly declared not to throw.
So clang-tidy has two options: It could do expensive (possibly inconclusive) control flow analysis or it can simply rely on you correctly declaring nothrow, which it does:
Finder->addMatcher(
varDecl(anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()),
unless(hasAncestor(functionDecl())),
anyOf(hasDescendant(cxxConstructExpr(hasDeclaration(
cxxConstructorDecl(unless(isNoThrow())).bind("func")))),
//^^^^^^^^^^^^^^^^^^^
hasDescendant(cxxNewExpr(hasDeclaration(
functionDecl(unless(isNoThrow())).bind("func")))),
//^^^^^^^^^^^^^^^^^^^
hasDescendant(callExpr(hasDeclaration(
functionDecl(unless(isNoThrow())).bind("func"))))))
.bind("var"),
this);

The language definition doesn't give you any guarantees here, but since virtually every implementation (that is, there are none I know of that don't) implements IEEE-754 math, which does not throw exceptions, it's not something I'd worry about. And more generally, a floating-point math package that throws exceptions would have had to be written with C++ in mind; that's highly unlikely.
However, you may well get messages when a floating-point error occurs that refer to a "floating-point exception"; that's a floating-point exception, not a C++ exception, and it has nothing to do with C++ exceptions. It's a runtime error, with a peculiar name.

Arithmetic cannot throw an exception in C++. With the usual caveat that if code causes undefined behaviour then anything can happen. So you can mark your function as noexcept.
Floating point multiplication may cause undefined behaviour if the result would be out of range.
The "floating point exceptions" are flags that don't interrupt your program: you must test for them using std::fetestexcept and then you can decide what to do. Several of the FE_ flags listed here may be raised by floating point multiplication.

Related

how to detect logic_error exception before runtime?

c++ standard says that logic_error could detect before runtime
while runtime_error detect at runtime.
but how is it working?
My question is how to detect logic_error before runtime.
could you give me some example? thanks for help~!
The C++ standard says this about logic_error (ยง22.2.2) :
The class logic_error defines the type of objects thrown as exceptions to report errors presumably detectable before the program executes, such as violations of logical preconditions or class invariants.
This does not mean that the exception can be caught at compile time. It means that the cause of the exception could be detected through other means (compiler warnings, code analysis, etc.) at compile time.
I think your misunderstanding is between what causes the exception to be thrown and the exception itself. There are exceptions that cannot be avoided even in a completely bug-free program, for example ones caused by user input. Then there are other exceptions that are clearly caused by writing logically wrong code. Consider this function:
double sqrt(double x); // takes only positive numbers
Now if I use this function like this:
double y = sqrt(-2);
then I made a logic error. I didnt respect the preconditions on the parameter to the function. In such a case it could be the right thing (*) to do for sqrt to throw a std::logic_error (as opposed to a plain runtime_error).
double sqrt(double x) {
if (x < 0) throw std::logic_error();
//....
Now when you read somewhere that "logic errors can be detected before runtime" then this most likely refers to the fact that one can read the code and see that calling sqrt(-2) is indeed wrong and fix it. However, note that this is unrelated to the actual exception being thrown (which is purely a runtime concept).
So to answer your question literally: You detect logic errors in your code by careful analysis. Pay attention to compiler warnings, ask co-workes for a review, use static analysis tools, etc.
(*) = maybe logic_error isnt the perfect thing to throw here, so please take the example with a grain of salt.

Noexcept specifier: why no compile time checks? [duplicate]

I am curious about the rationale behind noexcept in the C++0x FCD. throw(X) was deprecated, but noexcept seems to do the same thing. Is there a reason that noexcept isn't checked at compile time? It seems that it would be better if these functions were checked statically that they only called throwing functions within a try block.
Basically, it's a linker problem, the standards committee was reluctant to break the ABI. (If it were up to me, I would do so, all it really requires is library recompilation, we have this situation already with thread enablement, and it's manageable.)
Consider how it would work out. Suppose the requirements were
every destructor is implicitly noexcept(true)
Arguably, this should be a strict requirement. Throwing destructors are always a bug.
every extern "C" is implicitly noexcept(true)
Same argument again: exceptions in C-land are always a bug.
every other function is implicitly noexcept(false) unless otherwise specified
a noexcept(true) function must wrap all its noexcept(false) calls in try{}catch(...){}
By analogy, a const method cannot call a non-const method.
This attribute must manifest as a distinct type in overload resolution, function pointer compatibility, etc.
Sounds reasonable, right?
To implement this, the linker needs to distinguish between noexcept(true) and noexcept(false) versions of functions, much as you can overload const and const versions of member functions.
So what does this mean for name-namgling? To be backwards-compatible with existing object code we would require that all existing names are interpreted as noexcept(false) with extra mangling for the noexcept(true) versions.
This would imply we cannot link against existing destructors unless the header is modified to tag them as noexcept(false)
this would break backwards compatibility,
this arguably ought to be impossible, see point 1.
I spoke to a standards committe member in person about this and he says that this was a rushed decision, motivated mainly by a constraint on move operations in containers (you might otherwise end up with missing items after a throw, which violates the basic guarantee). Mind you, this is a man whose stated design philosophy is that fault intolerant code is good. Draw your own conclusions.
Like I said, I would have broken the ABI in preference to breaking the language. noexcept is only a marginal improvement on the old way. Static checking is always better.
If I remember throw has been deprecated because there is no way to specify all the exceptions a template function can throw. Even for non-template functions you will need the throw clause because you have added some traces.
On the other hand the compiler can optimize code that doesn't throw exceptions. See "The Debate on noexcept, Part I" (along with parts II and III) for a detailed discussion. The main point seems to be:
The vast experience of the last two decades shows that in practice, only two forms of exceptions specifications are useful:
The lack of an overt exception specification, which designates a function that can throw any type of exception:
int func(); //might throw any exception
A function that never throws. Such a function can be indicated by a throw() specification:
int add(int, int) throw(); //should never throw any exception
Note that noexcept checks for an exception thrown by a failing dynamic_cast and typeid applied to a null pointer, which can only be done at runtime. Other tests can indeed be done at compile time.
As other answers have stated, statements such as dynamic_casts can possibly throw but can only be checked at runtime, so the compiler can't tell for certain at compile time.
This means at compile time the compiler can either let them go (ie. don't compile-time check), warn, or reject outright (which wouldn't be useful). That leaves warning as the only reasonable thing for the compiler to do.
But that's still not really useful - suppose you have a dynamic_cast which for whatever reason you know will never fail and throw an exception because your program is written so. The compiler probably doesn't know that and throws a warning, which becomes noise, which probably just gets disabled by the programmer for being useless, negating the point of the warning.
A similar issue is if you have a function which is not specified with noexcept (ie. can throw exceptions) which you want to call from many functions, some noexcept, some not. You know the function will never throw in the circumstances called by the noexcept functions, but again the compiler doesn't: more useless warnings.
So there's no useful way for the compiler to enforce this at compile time. This is more in the realm of static analysis, which tend to be more picky and throw warnings for this kind of thing.
Consider a function
void fn() noexcept
{
foo();
bar();
}
Can you statically check if its correct? You would have to know whether foo or bar are going to throw exceptions. You could force all functions calls to be inside a try{} block, something like this
void fun() noexcept
{
try
{
foo();
bar();
}
catch(ExceptionType &)
{
}
}
But that is wrong. We have no way of knowing that foo and bar will only throw that type of exception. In order to make sure we catch anything we'd need to use "...". If you catch anything, what are you going to do with any errors you catch? If an unexpected error arises here the only thing to do is abort the program. But that is essentially what the runtime check provided by default will do.
In short, providing enough details to prove that a given function will never throw the incorrect exceptions would produce verbose code in cases where the compiler can't be sure whether or not the function will throw the wrong type. The usefulness of that static proof probably isn't worth the effort.
There is some overlap in the functionality of noexcept and throw(), but they're really coming from opposite directions.
throw() was about correctness, and nothing else: a way to specify the behavior if an unexpected exception was thrown.
The primary purpose of noexcept is optimization: It allows/encourages the compiler to optimize around the assumption that no exceptions will be thrown.
But yes, in practice, they're not far from being two different names for the same thing. The motivations behind them are different though.

C++/GCC: How to detect unhandled exceptions in compile time

Introduction:
In Java, if you do not catch an exception, your code doesn't even compile, and the compiler crashes on unhandled exception.
Question:
Is there a way to tell GCC to be "strict" as Java in this case, and to raise an error or at least a warning on unhandled exception?
If not - are there IDEs (for Unix, please) that can highlight such cases as a warning?
It is not possible in C++. Exception specification is a part of a function declaration but not a part of its type. Any indirect call (via pointer or virtual call) just completely wipes any information about exceptions.
Exception specifications are deprecated anyway in C++11 in favour of noexcept, so it is unlikely any compiler would bother to enhance this language feature.
The only guarantee you can put on a C++ function is that it never throws an exception at all:
void f() noexcept;
However, this will terminate the program at runtime when an exception is thrown. It's not verified at compile-time.
If you want to guarantee that an error is handled, the closest you can get is returning a value of a type that wraps boost::variant<OK, Error> with a member function that takes two callbacks: a callback for the OK case and one for the Error case.
You can ALWAYS use:
int main()
{
try {
... your usual main ...
}
catch(...)
{
std::cerr << "Unhandled exception caught" << std::endl;
}
}
However, that is a fairly poor solution.
Unfortunately, the nature of C++ makes it very hard to catch the situation where something throws an exception and it's not handled, since just about everything has the potential to throw exceptions. I can only think of code-review - perhaps code analyzing tools, such as that built around CLANG will have the capability of doing this, but it probably won't be 100% accurate. In fact, I'm not even sure that the Clang Analyzer fully understands throw/try/catch currently, as it seems to not catch some fairly fundamental errors http://clang-analyzer.llvm.org/potential_checkers.html (see the "exceptions" heading).
First, your statement concerning Java is false; only certain
types of exceptions prevent the code from compiling. And for
the most part, those types of exceptions correspond to things
that are better handled by return codes. Exceptions are normally
only an appropriate solution when propagating an error through
a large number of functions, and you don't want to have to add
exception specifications for all of those functions.
That's really why Java makes its distinctions: exceptions that
derive from java.lang.Error should usually be crashes
(assertion failures and the like in C++); and exceptions that
derive from java.lang.RuntimeException should be exceptions in
C++. Neither are checked in Java, either, because it isn't
reasonable to have every function declare that it might throw
one of them.
As for the rest, the exceptions which you want to catch
immediately in the calling code, they are generally best handled
by return codes, rather than exceptions; Java may use exceptions
here because it has no out arguments, which can make using
return codes more awkward. Of course, in C++, you can also
silently ignore return codes, which is a drawback (but
historical reasons, etc.). But the real issue is the contract,
which is far more complex than function f might throw/return x;
it's more along the lines of "function f will throw/return x,
if condition c is met". And I know of no language which has
a means of enforcing that. In C++ (and for checked exceptions
in Java), exception specifications are more along the lines of
"function f will not throw anything but x". Which is generally
not very useful, unless "x" means all exceptions. In order to
write really robust code, you need a few functions which are
guaranteed never to throw. Interestingly enough, you can
specify this in C++, both pre-C++11 (throw()) and post
(noexcept); you cannot in Java, because you can't specify that
a function won't throw a java.lang.RuntimeError.
(Or a java.lang.Error, but that's less of an issue, since if
you get one of those, you're application is hosed anyway. Just
how are you expected to recover from
java.lang.VirtualMachineError? And of course, you can't
really expect to be able to recover from a segment violation in
C++ either. Although... java.lang.OutOfMemoryError derives
from java.lang.VirtualMachineError; although not easy, and not
always applicable, I've written C++ code which successfully
recovered from std::bad_alloc.)

Why are C++ exception specifications not checked at compile-time?

I just read that in the C++11 standard revision, exception specifications were deprecated. I previously thought specifying what your functions may throw is good practice, but apparently, not so.
After reading Herb Stutter's well-cited article, I cannot help but wonder: why on earth are exception specifications implemented the way they are, and why has the committee decided to deprecate them instead of having them checked at compile-time? Why would a compiler even allow an exception to be thrown which doesn't appear in the function definition? To me, this all sounds like saying "You probably shouldn't specify your function return type, because when you specify int f(), but return 3.5; inside of it, your program will likely crash." (i. e., where is the conceptual difference from strong typing?)
(For the lack of exception specification support in typedefs, given that template syntax is probably Turing-complete, implementing this sounds easy enough.)
The original reason was that it was deemed impossible to
reliably check given the body of existing code, and the fact
that no specifier means anything can throw. Which means that
if static checking was in force, the following code wouldn't
compile:
double
safeSquareRoot( double d ) throw()
{
return d > 0.0 ? sqrt( d ) : 0.0;
}
Also, the purpose of exceptions are to report errors over
a great distance, which means that the intermediate functions
shouldn't know what the functions they call might throw.
Requiring exception specifiers on them would break
encapsulation.
The only real case where a function needs to know about the
exceptions that might occur is to know what exceptions cannot
occur. In particular, it is impossible to write thread safe code
unless you can be guaranteed that some functions will never
throw. Even here, static checking isn't acceptable, for the
reasons explained above, so the exception specification is
designed to work more like an assertion that you cannot
disactivate: when you write throw(), you get more or less the
equivalent of an assertion failure if the function is terminated
by an exception.
The situation in Java is somewhat different. In Java,
there are no real out parameters, which means that if you can't
use return codes if the function also has a return value. The
result is that exceptions are used in a lot of cases where
a return code would be preferable. And these, you do have to
know about, and handle immediately. For things that should
really be exceptions, Java has java.lang.RuntimeException
(which isn't checked, statically or otherwise). And it has no
way of saying that a function cannot ever throw an exception; it
also uses unchecked exceptions (called Error) in cases where
aborting the program would be more appropriate.
If the function f() throw(int) called the function g() throw(int, double) what would happen?
A compile time check would prevent your function from calling any other function with a less strict throw specifier which would be a huge pain.

Why is C++0x's `noexcept` checked dynamically?

I am curious about the rationale behind noexcept in the C++0x FCD. throw(X) was deprecated, but noexcept seems to do the same thing. Is there a reason that noexcept isn't checked at compile time? It seems that it would be better if these functions were checked statically that they only called throwing functions within a try block.
Basically, it's a linker problem, the standards committee was reluctant to break the ABI. (If it were up to me, I would do so, all it really requires is library recompilation, we have this situation already with thread enablement, and it's manageable.)
Consider how it would work out. Suppose the requirements were
every destructor is implicitly noexcept(true)
Arguably, this should be a strict requirement. Throwing destructors are always a bug.
every extern "C" is implicitly noexcept(true)
Same argument again: exceptions in C-land are always a bug.
every other function is implicitly noexcept(false) unless otherwise specified
a noexcept(true) function must wrap all its noexcept(false) calls in try{}catch(...){}
By analogy, a const method cannot call a non-const method.
This attribute must manifest as a distinct type in overload resolution, function pointer compatibility, etc.
Sounds reasonable, right?
To implement this, the linker needs to distinguish between noexcept(true) and noexcept(false) versions of functions, much as you can overload const and const versions of member functions.
So what does this mean for name-namgling? To be backwards-compatible with existing object code we would require that all existing names are interpreted as noexcept(false) with extra mangling for the noexcept(true) versions.
This would imply we cannot link against existing destructors unless the header is modified to tag them as noexcept(false)
this would break backwards compatibility,
this arguably ought to be impossible, see point 1.
I spoke to a standards committe member in person about this and he says that this was a rushed decision, motivated mainly by a constraint on move operations in containers (you might otherwise end up with missing items after a throw, which violates the basic guarantee). Mind you, this is a man whose stated design philosophy is that fault intolerant code is good. Draw your own conclusions.
Like I said, I would have broken the ABI in preference to breaking the language. noexcept is only a marginal improvement on the old way. Static checking is always better.
If I remember throw has been deprecated because there is no way to specify all the exceptions a template function can throw. Even for non-template functions you will need the throw clause because you have added some traces.
On the other hand the compiler can optimize code that doesn't throw exceptions. See "The Debate on noexcept, Part I" (along with parts II and III) for a detailed discussion. The main point seems to be:
The vast experience of the last two decades shows that in practice, only two forms of exceptions specifications are useful:
The lack of an overt exception specification, which designates a function that can throw any type of exception:
int func(); //might throw any exception
A function that never throws. Such a function can be indicated by a throw() specification:
int add(int, int) throw(); //should never throw any exception
Note that noexcept checks for an exception thrown by a failing dynamic_cast and typeid applied to a null pointer, which can only be done at runtime. Other tests can indeed be done at compile time.
As other answers have stated, statements such as dynamic_casts can possibly throw but can only be checked at runtime, so the compiler can't tell for certain at compile time.
This means at compile time the compiler can either let them go (ie. don't compile-time check), warn, or reject outright (which wouldn't be useful). That leaves warning as the only reasonable thing for the compiler to do.
But that's still not really useful - suppose you have a dynamic_cast which for whatever reason you know will never fail and throw an exception because your program is written so. The compiler probably doesn't know that and throws a warning, which becomes noise, which probably just gets disabled by the programmer for being useless, negating the point of the warning.
A similar issue is if you have a function which is not specified with noexcept (ie. can throw exceptions) which you want to call from many functions, some noexcept, some not. You know the function will never throw in the circumstances called by the noexcept functions, but again the compiler doesn't: more useless warnings.
So there's no useful way for the compiler to enforce this at compile time. This is more in the realm of static analysis, which tend to be more picky and throw warnings for this kind of thing.
Consider a function
void fn() noexcept
{
foo();
bar();
}
Can you statically check if its correct? You would have to know whether foo or bar are going to throw exceptions. You could force all functions calls to be inside a try{} block, something like this
void fun() noexcept
{
try
{
foo();
bar();
}
catch(ExceptionType &)
{
}
}
But that is wrong. We have no way of knowing that foo and bar will only throw that type of exception. In order to make sure we catch anything we'd need to use "...". If you catch anything, what are you going to do with any errors you catch? If an unexpected error arises here the only thing to do is abort the program. But that is essentially what the runtime check provided by default will do.
In short, providing enough details to prove that a given function will never throw the incorrect exceptions would produce verbose code in cases where the compiler can't be sure whether or not the function will throw the wrong type. The usefulness of that static proof probably isn't worth the effort.
There is some overlap in the functionality of noexcept and throw(), but they're really coming from opposite directions.
throw() was about correctness, and nothing else: a way to specify the behavior if an unexpected exception was thrown.
The primary purpose of noexcept is optimization: It allows/encourages the compiler to optimize around the assumption that no exceptions will be thrown.
But yes, in practice, they're not far from being two different names for the same thing. The motivations behind them are different though.