lexical_cast int to string
Asked Answered
L

3

13

Is it safe to ignore exception of boost::lexical_cast when converting int to std::string?

Liquid answered 29/4, 2010 at 9:16 Comment(8)
What do you mean by "ignore"?Tiffaneytiffani
I don't see why this cast can fail, therefore I want to perform cast without catching bad_lexical_castLiquid
You should ALWAYS wrap calls that can throw in try, catch blocks.Pearce
@Pearce Remarkably bad advice.Tiffaneytiffani
@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.Romeliaromelle
#2737828Leopardi
How about some of the examples from the following: 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.Katheryn
^ 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?Mazard
C
17

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.

Crocus answered 29/4, 2010 at 9:54 Comment(1)
Note that I said as the poster "when converting an int to std::string"Crocus
T
6

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.

Tiffaneytiffani answered 29/4, 2010 at 9:44 Comment(0)
C
0

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.

Christenachristendom answered 24/6, 2010 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.