Is it safe to ignore exception of boost::lexical_cast
when converting int
to std::string
?
-
What do you mean by "ignore"? – Apr 29 '10 at 09:20
-
I don't see why this cast can fail, therefore I want to perform cast without catching bad_lexical_cast – dimba Apr 29 '10 at 09:24
-
You should ALWAYS wrap calls that can throw in try, catch blocks. – Konrad Apr 29 '10 at 11:00
-
27@Konrad Remarkably bad advice. – Apr 29 '10 at 11:51
-
7@Konrad: Partly it depends on what you consider "wrap". There should be a try/catch block at the appropriate level to handle the exception, except sometimes in debug mode when you just want it to show on the debugger. This isn't necessarily anywhere near where the exception is thrown. In this case, I don't think `boost::lexical_cast` can throw anything besides `bad_alloc`, and normally there's nothing to do about that locally. Usually you'd catch it only to provide a reasonable message for end users. – David Thornley Apr 29 '10 at 13:25
-
2http://stackoverflow.com/questions/2737328/why-should-i-not-wrap-every-block-in-try-catch – Callum Rogers May 01 '10 at 17:03
-
11How about some of the examples from the following: http://www.codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant - they don't throw exceptions but rather return a bool indicating a success or failure. – Nov 04 '10 at 01:46
-
^ Here I was thinking a major reason for exceptions was to avoid reliance upon return codes. What if those functions needed to return other, actually useful (i.e. non-exceptional) values? – underscore_d Dec 16 '15 at 13:45
3 Answers
Exception raised by lexical cast when converting an int
to std::string
are not associated to the conversion, but to resource unavailable. So you can ignore this in the same way you ignore the exception bad_alloc
raised by operator new.

- 110,860
- 49
- 189
- 262

- 4,305
- 1
- 25
- 39
-
Note that I said as the poster "when converting an int to std::string" – Vicente Botet Escriba Dec 30 '11 at 13:33
As you say, I don't believe the cast can fail for the numerical types for conversion reasons - it can still fail because the string cannot be allocated, of course, but people don't normally catch that error except at the highest level of their code.
If you "ignore" an exception it will propagate back up the call stack until it is caught elsewhere, or it terminates the program, the point being you can safely not catch exceptions without worrying about you program continuing and doing unsafe/unknown things (as long as a "crash" to command prompt is acceptable error behaviour or you have some other way of dealing with unknown exceptions).
Unfortunately exception stack traces aren't so easy to get in C++, so creating useful error messages when exceptions aren't caught locally isn't always easy.

- 11,175
- 7
- 38
- 46