Conventions for using std::feclearexcept - c++

Is there any convention for using std::feclearexcept? In the examples you usually see, this is called before an operation is executed that might trigger a floating point exception. This seems a safe thing to do.
But should you also call std::feclearexcept after you have detected and handled an error, so that the error state does not persist throughout the rest of the program's execution?
If you would always call std::feclearexcept before checking for floating point exceptions, and if you would always check all operations that could trigger such exceptions, then this would be redundant. But these are a lot of ifs and an unlikely situation in real software, at least from my experience.

Simlar in reasoning to (re-)setting errno only before you do a specific operation and intend to check errno afterwards.
There might be conditions under which errno, or the floating point exception flags, are set that you are not aware of. You don't know where exactly they happened or what they mean semantically. You are not equipped to handle a situation of "uh, there was an overflow somewhere in the past but I don't know what it means".
Thus, you reset errno / call std::feclearexcept right before you execute a specific operation where you want to know the exact result / error condition, and do know how to handle it.
Resetting the error flags after that operation serves no purpose.

Related

When do I need to use throw and return?

I saw a function that uses throw to return something.
I've made some research before asking this, here, about throw and I did not find very much.
If someone could explain me when to use throw to return something and when to use the normal return statement, that would be awesome.
Using throw to return a result can be useful in a deeply nested recursion. Instead of backing out of each call level you get right back up to the top level call for this goal. I think in most other situations it's both too inefficient (because exceptions are optimized for failure handling) and too unconventional to even consider.
return is the easiest and in many situations also the most efficient way to return a computed value, a reference to a class member, a state information (e.g. an enum value), a trivial success/failure information, and, and, and. So this is the most common and usual way to evaluate function values.
throw on the other hand (like Alf already answered) deals with exception's - which, as the name already pretty clearly states :) an exception of the normal control flow: "Something very important (often something bad) happened, which requires an instant handling, I can not continue my usual processing flow and have to throw an exception immediately.". The reason can sometimes be a catastrophic and unrecoverable state in the program, but by no means always. For example, a socket losing its connection is pretty common and not a catastrophy - but can be a reason for throwing an exception nevertheless, because the socket code may be not able to continue computing.
Exceptions are usually a bit more difficult to handle - and to integrate into your program design - than usual return values, and they are - as others already stated - less efficient than simple return values, but they have a lot of benefits.
They can be caught from anywhere in the stack of calling functions
Let's say you write a game, with a game engine (e.g. Ogre), and this engine uses a direct X interface. Now something deep, deep in the DirectX interface happens, which hinders the engine from working correctly.
The error handling of this function (may be 8-10 calls deep in the call stack), which can not work properly anymore, would be nearly impossible if it would be done with normal return values - both for the engine programmers and for the game programmer. So in that case, without exceptions, the method of choice would be a non-standardized error handler - pretty similar to an exception, but not with the powerful possibilities of exceptions. Here's a practical example on how to handle this error with an exception (please ignore the real purpose of the functions, it's just to show the principle:
try
{
mHOQList[mCurrentFrame]->endOcclusionQuery();
} catch( Ogre::Exception& e )
{
if( e.getNumber() == Exception::ERR_RENDERINGAPI_ERROR
&& stdEx::string(e.getDescription()).beginsWith( "End occlusion called" ))
{
// a device lost occurred during our occlusion query. Simply ignore it.
return true;
}
else
throw;
}
We are doing an occlusion query here, which we know can not continue when a "device lost" event happens during it's operation. So we place it in a try/catch clause. When everything works out good in the endOcclusionQuery(), the catch() is never called, and everything is fine.
If an exception is thrown, we first check if we can handle it. We check the number of the exception and its description. If these informations have a specific value, we know that it's a benign error, we can safely ignore it and carry on the next frame. If we don't know how to handle it, we simply throw;, which leaves the handling of the exceplion to a catch() lower in the call hierarchy, which brings me to the next points:
They can be evaluated selectively.
The example above will catch and handle exceptions of the type Ogre::Exception, but nothing else. A std::exception or another exception type is not caught. Let's say for example the endOcclusionQuery() calls a callback in our own code, which then also gets into an exceptional state and throws. We would let this exception pass by and leave it to the lower (or higher) levels of the call hierarchy to handle it.
They can be rethrown.
In the example, we use throw; to re-throw and pass the handling to lower levels in the call hierarchy.
They can be stored and even re-thrown in a separate thread
Imagine a library with hundreds of worker threads, and a manager thread which coordinates these threads. Since exceptions are bound to a single thread, so the manager thread can never catch exceptions from the worker threads. But the worker threads can catch their own exceptions and either handle them if possible or store them, pass them to the manager thread, where it can be rethrown and be handled by the manager thread.
They can be thrown in Constructors
Constructors have no return value, and so it is impossible to check its success with return values. State members are possible, but awkward - they tend to be overlooked. So the preferrable way to deal with errors in a constructor is to throw (of course as a documented behavior). See also Throwing exceptions from constructors
They are standardized
Well when it comes to this, the example above is not the best. Ogre is a pretty old engine, long before C++11, and so the exception classes are proprietary. You can throw anything - from a char to a class LiverSausage. But today this shouldn't be done anymore - std::exception is the class of choice. It contains everything which is needed for a simple exception, and can be inherited for more sophisticated exceptions. It is commonly used and inherited in the STL, and there are helpers classes and functions like std::exception_ptr, std::current_exception() etc.
They can be used as a safe bailout for an unrecoverable program error. At the end, something ugly like this unfortunately can happen in the best programs. You can throw this fatal exception anywhere in your program, and you can catch this exception at a single place, where you can log the error, evaluate where it came from, perhaps even write a dump - so you have at least a clue what could have happened, which is at least less worse than simply crashing ;)
throw isn't used to return any value , it is used to throw exceptions i.e. if you think that a certain condition in the program is going to cause a runtime error or malfunction then you throw a exception which helps to avoid and deal with such runtime errors. Return is used to return from a function and a value to the calling function.
While this might sound bad, I actually let performance be a strong factor in guiding this decision. Most modern optimizers implement what's called zero-cost exception-handling, which ultimately translates to something like, "branch-free normal execution paths, but expensive exceptional paths".
It makes throwing quite expensive in exchange for making your normal execution paths really cheap. I don't have precise numbers for the costs but it's probably relatively extremely expensive if you're using a try/catch block just to test if a key exists in a data structure, e.g.
The other guiding force that I've found useful is the idea of an external exception outside of the programmer's control. Examples of that might be a client failing to connect to a server which should be up after repeated attempts, encountering a corrupt file, failing to allocate memory, things of this sort.
I did get into a debate one time with a colleague about whether a user jamming an abort button on a progress bar qualifies as an exceptional circumstance. I really thought it did because the operation is normally supposed to succeed, and a user aborting is a truly exceptional circumstance outside of the developer's control. On top of that it really simplified the code quite a bit over trying to propagate an abort status down the entire call stack.
In these cases where people might not agree about what is and isn't exceptional control flow, I use performance as like the deciding factor. Here throwing to abort an expensive operation isn't a big performance overhead, since it's not like we're throwing a million times in a critical loop. We're just throwing one time to abort a very expensive operation, and there the overhead of throwing becomes quite trivialized. So that's what I mean when I talk about performance being a deciding factor.

How to handle failed methods: by using exceptions or making the methods return bool?

How to handle failed methods:
using exceptions
making the methods return bool
The first approach is when something goes wrong to throw an exception.
But the problematic code needs to be placed in a try block,
and then you need to write the catch block.
The second approach you need to check the return value from
the method, and then do something.
So basically isn't it the same mechanism? You have two parts:
detecting that something goes wrong and then doing something about it.
So does it matter then which approach I use?
The main benefit with exceptions is that they are non-local. You can catch an exception several invocation layers away from where it was thrown. That way, code in between doesn't have to care about exceptions (except ensuring proper cleanup during unwinding, i.e. being exception safe), which makes it less likely that an exceptional situation gets forgotten. But this benefit comes at a price: stack unwinding is more complicated than simply returning a value. In terms of performance, the return value approach is usually simpler.
So I'd use these to choose: if for some reason the only reasonable place to deal with a problem is directly at the location where the function was called, and if you are fairly certain that every caller will include some kind of error handling code in any case, and is not likely to forget doing so, then a return value would be best. Otherwise, I'd go for an exception.
Basically you can reach the same behavior with both approaches, but Exception can give 2 added values:
1) You don't have to handle the error in the exact calling method, it can be anywhere up the call stack. this remove the if(!doSomthing()) return false; from the code when you just want to pass the error up.
2) It allow you to write a block of code, under one try and handle all the errors under it in one catch block.
There is no simple answer. For instance, here is the conclusion of the article C++ Exceptions: Pros and Cons
There is no simple answer to the "exceptions or error codes" question. The decision needs to be made based on a specific situation that a development team faces. Some rough guidelines may be:
If you have a good development process and code standards that are actually being followed, if you are writing modern-style C++ code that relies on RAII to clean up resources for you, if your code base is modular, using exceptions may be a good idea.
If you are working with code that was not written with exception safety in mind, if you feel there is a lack of discipline in your development team, or if you are developing hard real-time systems, you should probably not use exceptions.
My personal rule is to raise exception only when something exceptional occurs, ie when the problem may not have appeared at all. Otherwise I use return value (most of the time).
For example, when searching for a file that MUST exists, not finding it raises an exception. But if the file may or may not exists, not finding it is not exceptional so no need for an exception.
There's no answer for all situations. Both approaches have strengths and weaknesses:
Exceptions:
are slightly more verbose to handle locally
can simply be ignored if the error can't be handled locally
can carry as much information as you like about the error, both statically (in the exception type) and dynamically (in the thrown object)
require a handler somewhere to avoid terminating the program
may have more runtime overhead (but may have less when nothing is thrown, depending on how they're implemented)
require the code to be exception safe
Return values:
must be manually passed up the stack if not handled locally: prone to bugs if you forget
have a fixed type, limiting how much information they can carry (although you could return a pointer to a polymorphic type, and deal with the associated lifetime management issues)
are awkward to use if the function also needs to return something on success
There are two main differences: (a) it is easier for the calling code to just silently ignore the boolean status code. (b) Exceptions provide more context than mere false. You can distinguish business-logic errors from I/O errors from input validation errors etc.
I prefer bools. I'd say its personal preference.
I have found it easier to read.

Throwing a logical error exception or just abort in a library?

I like very much the assert behaviour for testing invariants and pre-conditions in my code. I use it a lot. But now I am developing a library (C++) and I like the client (the programmer who uses the library) to know when he violates the precondition. I think is easier to see the application crashes and fix the problem than just throwing in a undefined behaviour.
I could just use assert in this situation, but when my library is ready a release build will disable the assert macro. I know I can keep it but I'm not sure I want to because there is a lot of internal asserts don't need being tested in release build.
An instance:
Some state machine has a maximum number of states that can be added. The limit is setted by the client in the constructor. Then, the client calls the method addState to add specific states, but of course, he can't add more states than he said initially.
Should I:
Just ignore states after the limit and, probably, start a state machine with undefined behaviour (at least to client perspective)?
Keep assertions alive and put an assertion at that point?
Throw an exception (some std::logic_error, I presume)?
Just print a message to stderr and abort the program?
I don't like 1. very much. The idea is tell the client what is he doing wrong.
Is this a situation to throw a logical error exception?
Is there another, better possibility?
Thanks.
Definitely, if a problem is "detectable", you should do something to inform the "user" of the error (some things are very hard to identify that it's gone wrong)
You use assert when the programmer does something directly wrong, and that is unlikely to happen in "normal use" of the code. E.g. if you have a pointer parameter that mustn't be NULL, doing assert(ptr != NULL) would be a sensible thing, likewise if you have an int that is a count of something, it probably shouldn't be negative (but then it should probably be unsigned?). These type of things don't necessarily need to be that clearly documented - just that the precondition "ptr must not be NULL" or "count should not be negative".
You use exceptions for something that MAY happen in normal running conditions, but really shouldn't. Such as running out of memory, or the "user" trying to add too many things to something that they had a reason to give a reasonable size in the first place. Exceptions should be clearly documented by the description of the function - "If you try to add more states than you have reserved space for, the exception x will be thrown".
I personally would think that a "custom" exception would make more sense than std::logic_error. In this case, perhaps too_many_states? The more distinct your exception is, the easier it is to determine where it came from and what it means. Nothing worse than getting some "generic" exception and not knowing how you ended up there - and when you search for it, there are hundreds of places it could have come from...

Exceptions vs. errno

As a C programmer, I don't have much experience with exceptions. I'm rather used to errno as a means of communicating errors across several function calls. That having said, I don't see the distinguishing feature of exceptions, so...
What is the fundamental difference between exceptions and using errno?
There are so many differences here it's hard to say where to start.
First of all, errno as used in C is a global variable; this means every routine that calls an errno-setting subroutine must check errno before performing any other work, if it cares about correctness. Luckily enough, errno is threadsafe.
C++ exceptions automatically unwind up the call stack until they find a function prepared to handle the fault. This means that in most cases users don't have to explicitly check every call for an error; instead they can collect error returns in one place. C++ exceptions can contain values other than integers, unlike errno.
You can casually ignore errno. Exceptions must be dealt with.
Of course I've seen my share of:
try {
// something
}
catch( ... ) {
// nothing
}
// continue as if nothing happened
and (Java)
try {
// something
}
catch( Throwable t ) {
// nothing
}
// continue as if nothing happened
BUT at least that kinda jumps out at you when you're plowing through someone else's mess.
I feel compelled to point out that writing correct programs in the face of exceptions is not easy. You do well to do some research on the subject, perhaps starting with Guru of the Week. Just look for the word exception.
1) Exceptions can be anything, not just an integer. So the data communicated is different.
2) Exceptions do non-local control flow, so you don't have to check at every level in the way that in practice with errno, you also return a value that indicates error and every caller checks for errors and bails out early if one has occurred. Conversely, error returns do local control flow, so you can always see exactly when errors are propagated through a given piece of code. This difference radically changes coding style. So the means of communicating are different too.
To me, the most important difference is that errno is easily ignored, whereas exceptions are pretty hard to ignore - the program will terminate if you end up ignoring them... Plus, exceptions are (well, should be) objects, so you can carry more useful information.
The other, very important difference is that exceptions can easily be handled at the point where the software can actually make an informed decision how to handle the problem, which is usually several levels up the call stack. That's not that easy to do with error codes.
One pattern which I've found useful on embedded systems is to have an error flag for each stream, but provide that an I/O operation which is attempted when the flag is set will fail immediately. Thus, code can do something like:
pkt_type = tcp_getbyte(my_stream, timeout);
pkt_length = tcp_getbyte(my_stream, timeout);
pkt_length |= tcp_getbyte(my_stream, timeout) << 8;
if (pkt_length < MAX_PACKET_LENGTH)
{
for (i=0; i<pkt_length; i++)
buffer[i] = tcp_getbyte(my_stream, timeout);
}
if (!my_stream->error)
{
/* Do something with packet */
}
If one attempt to get a byte times out, succeeding attempts will fail unconditionally, returning zero. It's not necessary to check every operation for failure; if something goes wrong, the system will end up behaving roughly as though tcp_getbyte() had thrown an exception, just not quite as fast.

Why use exception instead of returning error code [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Exceptions or error codes
Hi,
I am looking for some guidelines on when to use return values v/s exceptions.
Many thanks in advance.
Errors are often detected at a very low level in your code, but handled at a very high level. If you use return codes for these, you have to design all the intermediate levels to expect the low level code and propagate it up until something handles it. With exceptions, you only need to throw at the low level, and catch at the high level (if at all). As long as your intermediate level code uses RAII, you don't have to change any of that to do the error propagation.
So I often think about the type of error and where it's likely to be handled. If the caller is likely to handle the problem, because it's expected to be a common thing, then a return code is great. If the error is something catastrophic (cannot allocate a necessary resource), then the immediate caller cannot be expected to handle it.
Other things to consider: Exceptions cannot be ignored, return codes can. Use an exception when it would be dangerous for the problem to go unhandled.
Technically, exceptions cannot propagate back up through C code. (It works on many systems, but it's not portable nor guaranteed.) So if you've got a C library calling back into your C++ code, you probably shouldn't throw an exception from the callback. Likewise for thread boundaries, etc.
Some of this might repeat content, but here are simple hints as to use one or the other:
No proper sentinel value
Your function might not be able to use a sentinel value to signal an error because all possible values are used by the function as valid answers. This may happen in different situations, most notably integer numerical algorithms. 0 and -1 are often used as special values but some fairly common algorithms, including pow might not be able to use those (i.e. 0^1=0 and -1^3=-1). Therefore, choosing proper values becomes somewhat of an art, consistancy is an issue and users have to remember the error value for each and every special case.
Some APIs recognize this and (almost) never use a real return value but consistently rely on return-by-reference semantics and use the return value in all functions as a status code, being either some (standard) "success" value, or a function-specific error code. CUDA, for instance, has such a convention.
Propagate by default
Error codes are often stated to be "more efficient" (a comment in one of the other answers explains why this is not necessarily true). However, they suffer from 2 common problems.
You have to manually propagate the error up the call stack. This is often omitted (especially in example code and books, which is very irritating) because it litters the code with tiresome and error-prone handling code.
Erros are diluted at high levels because error codes between different APIs are often impossible to concialiate. Moreover, designing you own error codes that cover the union of all libraries' error codes is a herculian task.This is why, in many applications, you get an The operation failed. message instead of Ran out of disk space..
To address (1), exceptions are propagated by default. Intentionally ignoring an error becomes obvious in the code, instead of hidden. To address (2), exceptions use type system, preventing you from compiling a program that has conflicting error "values". Morever, using an exception class hierarchy you can represent "families" of related results. (Note: this is often misused, and people catch Exception instead of NoMoreDiskSpace and still display the generic The operation failed. message).
A matter of consistancy
Some people will recommend a mixture of both in their applications, but IMHO, this leads to a situation where both the systems are mis-used. In these hybrid conventions, exceptions are often not caught and error-codes not checked because of confusion. On one hand, because exceptions are used only for exceptional situations, it is assumed they will never occur, or simply cannot be handled. On the other hand, a failure returning an error code is assumed to be minor and is not handled at all. And of course it is left up to each programmer to decide whether an situation is exceptional or not, leading to lots of confusion between what error codes to check and what exceptions to catch.
Which ever system you choose, be sure to use it at its full strength, and be consistent about its use.
You can look at exceptions and return values as two different methods of communication between callers and callee's. Return value being nice and quick way of informing parent about stuff, and exception being the rude cousin, one that you can fire and let others know how bad it is 'down there'.
If you write code that tries to handle every situation, you'll fill it with return values, error codes etc. If you omit handling some situation that occurs log way down on the call stack, and want quick resolution for this - someone will show MessageBox at this point - but you can throw, and handle it at any appropriate level above. Maybe that's the answer to your question!
On second thought, here are some rules that might apply:
use bool return values for simple success/fail situations
use enum return values for somewhat more complex situations
use ret. values for classes that know of each other, for example that serve same purpose or are in same module
use exceptions to throw far and account for unforeseen situations. Translate system errors that are not previously thought of to some exception of yours that you can handle on some higher level
I guess that both methods are here to stay. With time, your judgement will say which to use on each occasion.
There is a performance impact when exceptions are thrown that is the reason why error codes are used for more frequent error conditions. Save exceptions for truly out of the ordinary problems.
For example - in the STL, std::find does not throw if no match is located. But vector::push-back throws if memory is exhausted.
C++ exceptions are supposed to be used only for exceptional errors.
They are particularly useful for when an error is so bad that the calling function can't, or indeed shouldn't, handle it, e.g. a memory exhaustion. A thrown exception unwinds the stack until the first try block that it sees (or maybe the first try block with an appropriate catch, which would make more sense). This allows you to catch an exceptional error from a deeply nested function call, and be guaranteed that the stack is clean down to the function with the try block.
This all comes with overhead though, so use return codes when you can handle the (unexceptional) error inside the calling routine.
Along with the discussions already presented in the questions linked to by bjskishore123 in his comment, there is a very interesting historical back-and-forth between Ned Batchelder and Joel Spolsky on the subject. You may not entirely agree with Ned, but his argument is well thought out and worth a read.
Life is simple if your function has nothing to return - it can return a success/fail code. But when your function already has a meaning to its return value then you need to use "signal values" to return error codes. Find methods that return -1, for example, are using signal values. Sometimes it's almost impossible to come up with good signal values. If a function returns the next available date, what shoud it return when there is no available date? There's really no "-1" type date. So this is one case where exceptions are a very helpful mechanism. (This also handles functions like constructors that don't return anything.)
Yes, throwing and catching an exception is slightly more expensive than checking an error code. But it can't be forgotten and many people find it more expressive. And, as mentioned in other answers, when there is a cascade of function calls it's awkward to have all the intermediary calls check the return value and pass it along back up the chain.
Use error codes when it is not unusual for something to go wrong. For example, code that opens a file or makes a network connection should not return exceptions - it is very common for there to be problems.
Use exceptions when it is unusual for something to go wrong - the failure is truly exceptional.
So, that can be simplified to:
Use error codes most of the time.