How do I stop the breadth-first search using Boost Graph Library when using a custom visitor? - boost-graph

Say I found the node that meets my criteria and I need to stop the search.

The solution is to throw an exception of your known type - then catch it on the calling side. From the FAQ:
How do I perform an early exit from an algorithm such as BFS?
Create a visitor that throws an exception when you want to cut off the search, then put your call to breadth_first_search inside of an appropriate try/catch block. This strikes many programmers as a misuse of exceptions, however, much thought was put into the decision to have exceptions has the preferred way to exit early. See boost email discussions for more details.

Related

What were the reasons to terminate boost graph searches via exceptions?

Early exit of algorithms in boost graph such as breadth first search should be done by throwing an exception according to the FAQ:
How do I perform an early exit from an algorithm such as BFS?
Create a visitor that throws an exception when you want to cut off the search, then put your call to breadth_first_search inside of an appropriate try/catch block. This strikes many programmers as a misuse of exceptions, however, much thought was put into the decision to have exceptions has the preferred way to exit early. See boost email discussions for more details.
I am interested in the actual "thoughts that were put into the decision". So far I failed to find the appropriate posts on the mailing list. The closest I found was this one, stating
If the graph is big, exiting the algorithm by throwing an exception might be
the most efficient way ;-). Of course, if you do many invocations on small
graphs, it may be the least efficient ;-(.
and this one:
If you have enough callbacks, you can surely do all the same things. I'm not
sure what loss of control you fear, but from an efficiency point-of-view it
might make sense to exit the algorithm by throwing an exception (no, I'm
really NOT kidding).
Which, to me, are no real well-founded justifications for the design decision. Also because we do see huge slow downs when a lot of exceptions are thrown, especially while running the code in a debugger.
I am also aware of similar posts on stackoverflow (such as this one or this one) asking on how to terminate the searches. But I know how (by throwing an exception). Yet, none of them provide the reasoning behind the decision.
So my question is: Does anyone know the actual thoughts that went into the decision? And does anyone have an actual link to the boost mailing list post that contains these thoughts that are alluded to in the FAQ?
It simplifies the implementation. It allows all searches to leverage a generic traversal algorithm.
The argument becomes amplified in the face of generics.
Note that the visitors can be implemented in several ways:
users can implement the visitor interface
derive from one and override some handlers
or
compose one from different Event Visitors
Especially that case creates questions with generic composition if handlers were to return a control value. What if several handlers handle the same event, how would the return values be combined?
This situation is similar to other event-driven designs, like browser script UI events (which can bubble up or not) or Boost Signals2 signal slots, which can have user-supplied combiners instead of the default optional_last_value
The key element is multiplicity of event handlers/"slots".
You might argue that this can be summarized as "the library doesn't afford early search termination", but as the documentation reflects the designers specifically opted to allow the exceptions language feature to be used here. In addition to all the places you already mentioned, let me quote from the implementation of the BGL function is_bipartite which uses a DFS that is potentially prematurely aborted when the graph is not bipartite:
try
{
depth_first_search(graph,
vertex_index_map(index_map).visitor(make_dfs_visitor(
std::make_pair(detail::colorize_bipartition(partition_map),
std::make_pair(detail::check_bipartition(partition_map),
put_property(partition_map,
color_traits< partition_color_t >::white(),
on_start_vertex()))))));
}
catch (const detail::bipartite_visitor_error< vertex_descriptor_t >&)
{
return false;
}
return true;

Exception propagation analysis in C++

Our code has certain guidelines as to which exceptions are
ad-hoc -- function boundary -- for handling rare error-situations within a single function, where other methods of flow control are impractical,
internal -- library boundary -- for communicating error-situations between several components within a library,
external -- main boundary -- for communicating error-situations across library-boundary, to foreign code.
To make sure the written library/foreign code conforms, I've done a semi-automated analysis of exception propagation, by:
filtering interesting throw statements with grep,
creating a potential call tree (with Eclipse/CDT) for each function not immediately handling the above-identified thrown exception
analyzing the call tree manually and checking whether the given exception is eventually handled no later than the relevant boundary
My question is, is there a static analyzer that does just this?
I think no matter at what you look at it would be custom. Don't know if a commercial tool is an option but I believe Klocwork might fit.
But this would involve using something they call KAST. A tool to create custom rules in an XPath type format. Pretty easy to create and powerful.
However with that said it is way overkill to use Klocwork just for this. Worth a look.
This seems relevant
Exception analysis tool for C++
But you're interested in the catch-points for exceptions. As far as my experience goes, static analyzers will only let you know about uncaught exceptions.

How should I handle exceptions in C++/Qt? [duplicate]

I was talking to a friend of mine that through my new code I didn't treat exceptions, just because I didn't know how to do it in C++. His answer surprised me: "why in the hell would you want to throw excetions?". I asked him why, but he didn't have a satisfying answer, so I googled it. One of the first pages I found was a blog entry, where the guy who posted wasn't totally against exceptions, but a religious war started in the replies: http://weblogs.asp.net/alex_papadimoulis/archive/2005/03/29/396141.aspx
Now I begin to wonder: is it that bad to throw an exception? For a student like I am, is it wrong to learn programming using exceptions as a normal thing? (When I throw exceptions, I catch them in another level of the code to treat them, most of the times). I have a code example, and I want to know what should I do:
int x;
cout << "Type an integer: ";
cin >> x;
Anything that is typed there that is not an integer will trigger an exception already, right? This exception should be treated there. But when I have a possible exception inside a class that is being used elsewhere in the program, should I make this method throw an exception so I can treat it wherever I call it or should I make it return a standard value when it has any problems?
The exception is always good, always bad, or something to be used in "exceptional" situations? Why?
The C++ iostreams classes do not, by default, use exception handling. Generally one should use exceptions for situations where an error can occur, but such errors are "unusual" and "infrequent" (such as a disk failing, the network being down, etc.). For error conditions that you do expect (such as the user providing invalid input), you should probably not use exception handling, unless the logic that needs to deal with this situation is far removed from the logic in which the situation is detected, in which case using an exception is the way to go. There is nothing wrong with using exceptions, and using exceptions where they are merited is definitely good... just avoid using them where if...else works just fine.
As to the why:
Exceptions often provide a simple, elegant way of handling unexpected errors, but:
Exception propagation, depending on the compiler and platform, may be slower than ordinary control flow, so if you can handle the situation locally, then that will be at least as fast... and you especially don't want to slow down the common, expected cases (such as invalid input). Also:
Exceptions require more type information to be present and also require code that is unrelated to throwing or catching exceptions to be "exception-safe" which is why some object to exceptions.
Question 1:
There is no reason not to use exceptions.
Whether to use exceptions or other techniques depends on the situation.
Exceptions are good to use when you can't fix the error locally.
(This should be an exceptional situation :-)
Error codes are good when you can fix the error locally.
Error codes are bad if you have a library that exposes an interface that returns an error code that needs to be manually checked. In the C world forgetting to check the error code was a significant source of problems.
Exceptions are good when you want to force the user of your interface to check for an error. If the user does not explicitly check and compensate; then the exception will propagate until either it is handled or the application exits.
Problems that come with exceptions:
If your code is a combination of C and C++. Functions with C ABI do not contain enough information for exceptions to propagate. Thus throwing an exception across a C function can (depending on the compiler and other factors) cause problems.
If you register a callback functions with a C library that uses C++ code. Then you must make sure that all exceptions are caught in the callback function and not allowed to propagate back to the C-library.
But this is true when combining any two languages. You can only use the most primitive features across language boundaries (and even that can take work if the languages do not align well). Therefore trying to use any advanced features is usually not supported.
Question 2:
C++ streams by default do not use exceptions.
This is because usually you want to handle the problem immediately.
In your example you use input as an example. In this situation you want to check the error and re-request the input.
int x;
cout << "Type an integer: ";
cin >> x;
while(!cin)
{
cin.clear();
std::cout << "Failed: What do you think an integer is? Try again: ";
cin >> x;
}
Note:
Personally I don't like the phrase 'Use exceptions in Exceptional circumstances". To me that is just to vague. vector::at() throws an exception. For me accessing off the end of an array is going to be exceptional (but for Joe student I doubt it will be exceptional (it will happen every second class as the lecturer throws a new curve ball at him/her)).
Thus I prefer the term "When the problem can not be fixed locally". A problem that can not be fixed locally is when something big has gone wrong (resource depletion (memory full throw bad_alloc()), coding error (access beyond array bounds (throw range_check()))) or any number of things that can not be fixed right there.
There is actually a legitimate reason behind why you shouldn't use exceptions.
The problem is when you throw exception across boundaries (e.g. from one DLL and try...catch it in another DLL) sometimes things can go very wrong. I got a slap on the wrist too when I used it in one of my projects.
Just google it you'll find all sorts of post on this topic, at least it was a problem few years ago when I was still a fulltime C++ developer :)
I tend to follow this convention for internal parts of my applications code:
Do not throw exceptions of your own.
Catch any exception that could be expected from your calls to other code inmediately. Treat it accordingly, for example returning an error code, or "false" with the meaning of no success.
However when designing components, I do use component-scope exceptions, like for example, if connecting to a required database (one which is set up by the installer) fails. Or when you try to call any method violating its preconditions. In general, preconditions are expressed with assertions; however, in the public layer of your component, they should be checked and an exception thrown if they are violated, otherwise the caller has a hard job finding what they are doing wrong. (An alternative is of course to use a debug version, in which failed assertions will scream at you; but this is not always practical - distributing two binaries, keeping them up to date, etc.)
In my opinion, the only general rule is to be consistent and write correct code - choose some way to handle the erroneous/exceptional situations, and follow it consistently.
I think exception handling/throwing can be boiled down to the following:
Use RAII (or using in C#, or with in Python) so your code is exception safe.
Catch exceptions if there's a chance to recover from the error, else let them bubble up.
Throw exception only if you have something useful to add.
Consider a hypothetical example where you're using a serial port communication library to communicate with an external sensor of sorts. Furthermore:
The serial port communication library reports errors by throwing exceptions.
The sensor itself can communicate certain error messages through status codes in cases when it's no longer able to acquire data, when it's functioning outside its max/min operating conditions, etc.
You're using RAII (Resource Acquisition Is Initialization), so if the serial port library throws an exception you wouldn't have to worry about releasing any acquired resources.
If the serial port library thrown an exception, you can:
Catch the exception and try to recover from it somehow, e.g. by reinitializing the library.
Catch the exception, wrap it in your own, and then throw the new exception up the call stack.
Option #1 is unlikely in most cases. And option #2 would probably not add any valuable information to what's already in the original exception.
So usually it's best to allow original exception to bubble up (this is again assuming the RAII is in place and no clean up is needed).
On the other hand, if the sensor itself reports an error code, then it makes a lot of sense to throw your own exception.
This one is also a very interesting and controversial reading on the argument:
http://blogs.msdn.com/b/oldnewthing/archive/2005/01/14/352949.aspx
Throw an exception if, and only if, the alternative is failure to meet a post condition or to maintain an invariant.
That advice replaces an unclear subjective decision (is it a good idea) with a technical, precise question based on design decisions (invariant and post conditions) you should already have made.
If you just blindly go and say I won't use exceptions it means you're not going to use most of the STL. That means you need to write your own classes for strings/vector etc etc ...
Plus exceptions are a much cleaner way of doing error handling (IMHO) and if you already do RAII then adding exceptions is not much harder.
Read everything in Section 14 upto section 14.2 of Bjarne Stroustrup: "C++ programming Language Third Edition"
It is the most convincing answer I have come across.

When and how to catch exceptions

I am working on a code-base with a bunch of developers who aren't primarily Computer Science or Software Engineering (Mostly Computer Engineering)
I am looking for a good article about when exceptions should be caught and when one should try to recover from them. I found an article a while ago that I thought explained things well, but google isn't helping me find it again.
We are developing in C++. Links to articles are an acceptable form of answer, as are summaries with pointers. I'm trying to teach here, so tutorial format would be good. As would something that was written to be accessible to non-software engineers. Thanks.
Herb Sutter has an excellent article that may be useful to you. It does not answer your specific question (when/how to catch) but does give a general overview and guidelines for handling exceptional conditions.
I've copied his summary here verbatim
Distinguish between errors and
nonerrors. A failure is an error if
and only if it violates a function's
ability to meet its callees'
preconditions, to establish its own
postconditions, or to reestablish an
invariant it shares responsibility for
maintaining. Everything else is not an
error.
Ensure that errors always leave your
program in a valid state; this is the
basic guarantee. Beware of
invariant-destroying errors
(including, but not limited to,
leaks), which are just plain bugs.
Prefer to additionally guarantee that
either the final state is either the
original state (if there was an error,
the operation was rolled back) or
intended target state (if there was no
error, the operation was committed);
this is the strong guarantee.
Prefer to additionally guarantee that
the operation can never fail. Although
this is not possible for most
functions, it is required for
functions such as destructors and
deallocation functions.
Finally, prefer to use exceptions
instead of error codes to report
errors. Use error codes only when
exceptions cannot be used (when you
don't control all possible calling
code and can't guarantee it will be
written in C++ and compiled using the
same compiler and compatible compile
options), and for conditions that are
not errors.
Read the chapter "Exception Handling" from the Book
Thinking in C++, Volume 2  - Bruce Eckel
May be this MSDN section will help you...
The most simplistic advice:
If you don't know whether or not catching an exception, don't catch it and let it flow, someone will at one point.
The point about exceptions is that they are exceptional (think std::bad_alloc). Apart from some weird uses for "quick exit" of deeply nested code blocks (that I don't like much), exceptions should be used only when you happen to remark something that you have no idea how to deal with.
Let's pick examples:
file = open('littlefile.txt', open.mode.Read)
It does seem obvious, to me, that this may fail, and in a number of conditions. While reporting the cause of failure is important (for accurate diagnostic), I find that throwing an exception here is NOT good practice.
In C++ I would write such a function as:
boost::variant<FileHandle,Error> open(std::string const& name, mode_t mode);
The function may either return a file handle (great) or an error (oups). But since it's expected, better deal with it now. Also it has the great advantage of being explicit, looking at the signature means that you know what to expect (not talking about exception specifications, it's a broken feature).
In general I tend to think of these functions as find functions. When you search for something, it is expected that the search may fail, there is nothing exceptional here.
Think about the general case of an associative container:
template <typename Key, typename Value>
boost::optional<Value const&> Associative::GetItem(Key const& key) const;
Once again, thanks to Boost, I make it clear that my method may (or not) return the expected value. There is no need for a ElementNotFound exception to be thrown.
For yet another example: user input validation is expected to fail. In general, inputs are expected to be hostile / ill formed / wrong. No need for exceptions here.
On the other hand, suppose my software deal with a database and cannot possibly run without it. If the database abstraction layer loses the connection to the database and cannot establish a new one, then it makes sense to raise an exception.
I reserve exceptions for technical issues (lost connection, out of memory, etc...).

To throw or not to throw exceptions?

I was talking to a friend of mine that through my new code I didn't treat exceptions, just because I didn't know how to do it in C++. His answer surprised me: "why in the hell would you want to throw excetions?". I asked him why, but he didn't have a satisfying answer, so I googled it. One of the first pages I found was a blog entry, where the guy who posted wasn't totally against exceptions, but a religious war started in the replies: http://weblogs.asp.net/alex_papadimoulis/archive/2005/03/29/396141.aspx
Now I begin to wonder: is it that bad to throw an exception? For a student like I am, is it wrong to learn programming using exceptions as a normal thing? (When I throw exceptions, I catch them in another level of the code to treat them, most of the times). I have a code example, and I want to know what should I do:
int x;
cout << "Type an integer: ";
cin >> x;
Anything that is typed there that is not an integer will trigger an exception already, right? This exception should be treated there. But when I have a possible exception inside a class that is being used elsewhere in the program, should I make this method throw an exception so I can treat it wherever I call it or should I make it return a standard value when it has any problems?
The exception is always good, always bad, or something to be used in "exceptional" situations? Why?
The C++ iostreams classes do not, by default, use exception handling. Generally one should use exceptions for situations where an error can occur, but such errors are "unusual" and "infrequent" (such as a disk failing, the network being down, etc.). For error conditions that you do expect (such as the user providing invalid input), you should probably not use exception handling, unless the logic that needs to deal with this situation is far removed from the logic in which the situation is detected, in which case using an exception is the way to go. There is nothing wrong with using exceptions, and using exceptions where they are merited is definitely good... just avoid using them where if...else works just fine.
As to the why:
Exceptions often provide a simple, elegant way of handling unexpected errors, but:
Exception propagation, depending on the compiler and platform, may be slower than ordinary control flow, so if you can handle the situation locally, then that will be at least as fast... and you especially don't want to slow down the common, expected cases (such as invalid input). Also:
Exceptions require more type information to be present and also require code that is unrelated to throwing or catching exceptions to be "exception-safe" which is why some object to exceptions.
Question 1:
There is no reason not to use exceptions.
Whether to use exceptions or other techniques depends on the situation.
Exceptions are good to use when you can't fix the error locally.
(This should be an exceptional situation :-)
Error codes are good when you can fix the error locally.
Error codes are bad if you have a library that exposes an interface that returns an error code that needs to be manually checked. In the C world forgetting to check the error code was a significant source of problems.
Exceptions are good when you want to force the user of your interface to check for an error. If the user does not explicitly check and compensate; then the exception will propagate until either it is handled or the application exits.
Problems that come with exceptions:
If your code is a combination of C and C++. Functions with C ABI do not contain enough information for exceptions to propagate. Thus throwing an exception across a C function can (depending on the compiler and other factors) cause problems.
If you register a callback functions with a C library that uses C++ code. Then you must make sure that all exceptions are caught in the callback function and not allowed to propagate back to the C-library.
But this is true when combining any two languages. You can only use the most primitive features across language boundaries (and even that can take work if the languages do not align well). Therefore trying to use any advanced features is usually not supported.
Question 2:
C++ streams by default do not use exceptions.
This is because usually you want to handle the problem immediately.
In your example you use input as an example. In this situation you want to check the error and re-request the input.
int x;
cout << "Type an integer: ";
cin >> x;
while(!cin)
{
cin.clear();
std::cout << "Failed: What do you think an integer is? Try again: ";
cin >> x;
}
Note:
Personally I don't like the phrase 'Use exceptions in Exceptional circumstances". To me that is just to vague. vector::at() throws an exception. For me accessing off the end of an array is going to be exceptional (but for Joe student I doubt it will be exceptional (it will happen every second class as the lecturer throws a new curve ball at him/her)).
Thus I prefer the term "When the problem can not be fixed locally". A problem that can not be fixed locally is when something big has gone wrong (resource depletion (memory full throw bad_alloc()), coding error (access beyond array bounds (throw range_check()))) or any number of things that can not be fixed right there.
There is actually a legitimate reason behind why you shouldn't use exceptions.
The problem is when you throw exception across boundaries (e.g. from one DLL and try...catch it in another DLL) sometimes things can go very wrong. I got a slap on the wrist too when I used it in one of my projects.
Just google it you'll find all sorts of post on this topic, at least it was a problem few years ago when I was still a fulltime C++ developer :)
I tend to follow this convention for internal parts of my applications code:
Do not throw exceptions of your own.
Catch any exception that could be expected from your calls to other code inmediately. Treat it accordingly, for example returning an error code, or "false" with the meaning of no success.
However when designing components, I do use component-scope exceptions, like for example, if connecting to a required database (one which is set up by the installer) fails. Or when you try to call any method violating its preconditions. In general, preconditions are expressed with assertions; however, in the public layer of your component, they should be checked and an exception thrown if they are violated, otherwise the caller has a hard job finding what they are doing wrong. (An alternative is of course to use a debug version, in which failed assertions will scream at you; but this is not always practical - distributing two binaries, keeping them up to date, etc.)
In my opinion, the only general rule is to be consistent and write correct code - choose some way to handle the erroneous/exceptional situations, and follow it consistently.
I think exception handling/throwing can be boiled down to the following:
Use RAII (or using in C#, or with in Python) so your code is exception safe.
Catch exceptions if there's a chance to recover from the error, else let them bubble up.
Throw exception only if you have something useful to add.
Consider a hypothetical example where you're using a serial port communication library to communicate with an external sensor of sorts. Furthermore:
The serial port communication library reports errors by throwing exceptions.
The sensor itself can communicate certain error messages through status codes in cases when it's no longer able to acquire data, when it's functioning outside its max/min operating conditions, etc.
You're using RAII (Resource Acquisition Is Initialization), so if the serial port library throws an exception you wouldn't have to worry about releasing any acquired resources.
If the serial port library thrown an exception, you can:
Catch the exception and try to recover from it somehow, e.g. by reinitializing the library.
Catch the exception, wrap it in your own, and then throw the new exception up the call stack.
Option #1 is unlikely in most cases. And option #2 would probably not add any valuable information to what's already in the original exception.
So usually it's best to allow original exception to bubble up (this is again assuming the RAII is in place and no clean up is needed).
On the other hand, if the sensor itself reports an error code, then it makes a lot of sense to throw your own exception.
This one is also a very interesting and controversial reading on the argument:
http://blogs.msdn.com/b/oldnewthing/archive/2005/01/14/352949.aspx
Throw an exception if, and only if, the alternative is failure to meet a post condition or to maintain an invariant.
That advice replaces an unclear subjective decision (is it a good idea) with a technical, precise question based on design decisions (invariant and post conditions) you should already have made.
If you just blindly go and say I won't use exceptions it means you're not going to use most of the STL. That means you need to write your own classes for strings/vector etc etc ...
Plus exceptions are a much cleaner way of doing error handling (IMHO) and if you already do RAII then adding exceptions is not much harder.
Read everything in Section 14 upto section 14.2 of Bjarne Stroustrup: "C++ programming Language Third Edition"
It is the most convincing answer I have come across.