I've run into a situation with some code I inherited... honestly, I believe the code is written correctly, but this error still seems to manifest.
I'll quickly note that the code is cross-compiled from linux to LynxOS, I'm not sure if that can have anything to do with the error.
Basically, in one specific case:
try {
std::vector<ClassA> x = SomeGeneratingFunction();
//We get to here fine. X may be empty/unpopulated though.
if (x.size() < 1)
{
throw(MyException("It crashed."));
}
}
catch (MyException e)
{
//Handle it.
}
catch (...)
{
//Handle it.
}
We throw given the vector is unpopulated, but for some reason the throw bypasses the catch clauses - both of them. It only seems to happen here - though we woudln't usually do it form an if statement scope, but that should be completely irrelevant since its still in the try scope.
PS: The code below is actually the contents of a function, and exceptions come out of the function when called even though they should all be handled by the catch blocks.
Any ideas how this is possible? And yes, this isn't the real code/exception classes, but the exception class is the simple example you'd google of overloading std::exception, and the SomeGeneratingFunction() does return a good vector, even if it is empty. I cannot provide the real code, but this is exceedingly close barring any little typos I may have made writitng it off the top of my head.
Since the catch (...) clause didn't catch the exception, my answer does not solve the OP's problem. But for others that found this question on SO, maybe my answer is useful, because it explains why the first catch failed.
I had a similar issue where my catch(const std::exception& ex) was just not working. It turned out to be a dumb problem in that I was switching between C# and C++ exceptions, and in C# you need to specify new when you throw your exception, while in C++ you normally don't (but you can, but in this case you are throwing a pointer and not a reference). I was accidentally doing
throw new std::runtime_error("foo");
so
catch(std::exception* ex)
would have caught it but
catch(std::exception& ex)
doesn't. Of course, the solution is just remove the new statement, as that is not the traditional design pattern in C++.
Since you have a spare set of parentheses around the exception object in the throw statement, it looks like a function call. Is there any possibility that you've defined a function called throw? The parameter to the exception constructor keeps this from being a victim of the Most Vexing Parse, but that's a possibility if your actual code differs from your example.
catch (MyException e)
should read:
catch (const MyException &e)
I'm not sure why your throw looks like a function either, kind of bizarre.
Edit:
I've had problems with catches based on something similar, though I agree that it isn't sufficient in this toy case.
The compiler seems off to me, is Try defined as something funny? If it were empty it could make sense if your compiler ignored catch statements with no try.
If you have a function MyException in a smaller scope (possibly even by accident, Most Vexing Parse) then throw MyException("It crashed") will call that function and throw the return value.
Let me slash the problem... Don't use exceptions in C++ unless you want to crash definitely the program. I know exceptions may be quite useful, but they have very poor performances because it raises up an hardware exception which is caught by the operating system kernel. Using return values and error codes can be 500 times faster than throwing and catching exceptions.
I would just rewrite it without using try/catch. Doesn't seem appropriate to use try/catch here anyway. For all you know, exceptions may not work on your target platform.
Related
I haven't done C++ in a while and my memory is fuzzy, nor have I found a definitive answer so far searching. I'm not talking about rethrowing the caught exception, but rather catching one exception and throwing a different type, such as:
std::unordered_map<int, int> foo;
...
int getFoo(int id)
{
try {
return foo.at(id);
}
catch (std::out_of_range& e)
{
throw MyMoreDescriptiveExceptionType();
}
}
Yes. (have to fill to reach 30 characters)
Yes. Among other things, it allows you to log and re-throw exceptions properly.
Just be careful to re-throw properly. If done incorrectly, you could lose the original stack trace which makes the actual problem much harder to track down.
Yes, it's entirely valid. It's actually quite a common thing to do. For example, a small utility class may throw a fairly generic exception. The code that was calling it may catch that exception, and wrap it in a more specific one, providing more useful information about the context. It will then throw that 'outer' exception.
The same catch-wrap-throw pattern can extended as many levels as you need, until something is able to address the problem or shutdown gracefully.
Yes and that thrown exception will be caught by the next catch in order or next upper level catch and so on
I am writing some library functions that needs to do some error reporting. I want to use exceptions rather than return values.
I wrote my functions that throws int exceptions.
Eg:
if(strm->atEnd()){
// unexpected end of stream
throw -2;
}
My question is, is this method OK? Or should I throw a exception derived from std::exception?
In what way is throwing a std::exception better? (Other than being able to use catch(std::exception &e))
Is throwing int exceptions bad practice? (all throw int values are documented in doxygen comments)
I can't find any reason as to why (in this case) should I throw an object.
I would throw an exception based on std::exception.
throw std::runtime_error("unexpected end of stream")
I find this easier to catch, log, et cetera. It also allows the removal of a comment and a magic number from the code.
This message can then be sent to the end-user to give them a hope of fixing the problem.
Users and library consumers can't read the comments in code, and they are unlikely to know what '-2' means.
Exception are for exceptional behaviour. They're the last thing that you should worry about optimizing!
Donald Knuth said:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil
Also, an object as exception may carry information about the error.
For example, you have an exception that means that a file cannot be read. If you throw an object exception, the object may carry the file name, which you cannot have with ints.
If the exception origin is unknown (deep in your stack) and no one catches it, it will be easier to debug the program if the exception is an object with proper information.
My question is, is this method OK?
Think about the readability. Wouldn't
throw CUnexpectedEndOfStream();
be more readable than
throw -2
?
And in a lot of cases wouldn't seeing an instance of CUnexpectedEndOfStream thrown in the debugger mean TONS more than -2. That's not to mention that CUnexpectedEndOfStream could store gobs of useful information about the problem such as say the file that couldn't be read and maybe more info on the nature of the problem.
Or should I throw a exception derived from std::exception?
Inheriting from std::exception may be helpful if that's how you choose to organize your other exceptions. It a convenient base class that client code can use. Also depending on the exception you may want to use std::runtime_error.
Is throwing int exceptions bad practice? (all throw int values are documented in doxygen comments)
Who said it was bad practice? Throwing exceptions is a great way to handle exceptional situations. Most of the exceptions I throw are because of something that could have been prevented by the client code doing what it was supposed to-- the user of my code violated the contract. But many other exceptional non-normal cases also exist like OS errors, disks filling up, etc. All the things that aren't part of your programs normal flow. More importantly, since they're not part of your program's normal flow, you don't need to worry about performance.
As an example, I once used exceptions to trigger that a certain message parsing failure occurred. However, I found that these parsing errors occurred frequently to the point where I started handling exceptions and fixing the problem input and reparsing. After a while, I realized that a more readable solution would be to fix the problem directly in the parsing code and stop treating it like an exceptional case. All the code that made parsing decisions was put back in one place and I wasn't throwing exceptions like a drunken sailor throws out curse words.
You should throw an exception derived from std::exception, e.g. std::runtime_error.
Most existing code assumes that an ordinary C++ exception is a std::exception, and anything else is a "hard exception" to be propagated up to a very high control level, like main.
For example, existing code will most probably not be able to log any reasonable message for your int. It will just be "unknown exception type".
Cheers & hth.,
Why don't you do this:
if(strm->atEnd()){
// unexpected end of stream
throw std::exception("-2");
}
throw -2 is bad because the type of -2 is neither std::exception nor derives from std::exception.
Or you should better write your own class as:
class FileException : public std::exception
{
//...
};
And then
throw FileException("Unexpected end of stream");
which is more readable.
I want to know, is it a good practice to place complete code inside a try block or I should place only the code which I feel it will cause a specific exception?
And should I catch basic Exception always
Code 1: complete code in try block
myFunction(){
try{
.........
Code with chance of OneException
.............
}catch(OneException e){
............
}catch(Exception e){
..............
}
}
Code 2: Only the Code with chance of Exception in try block
myFunction(){
.......
try{
Code with chance of OneException
}catch(OneException e){
............
}
............
}
Code 3:Should I catch Exception always
myFunction(){
.......
try{
Code chance of OneException
}catch(OneException e){
............
}catch(Exception e){
..............
}
........
}
Out of this (code1, code2 and code3) which one is the best?
I'm mainly concern with java and C++ coding
Generally speaking, you should only catch exceptions you're interested in and which you can handle. That is...catch an exception where you can do something s.t. the user doesn't perceive the problem or when it is explicitly necessary to tell the user about the problem.
For all other exceptions, let them pop up with all their details (stacktrace etc..) which you obviously log. Note, obviously this doesn't mean the user should also see that exception output but rather a generic error.
Told this, I assume that when you write "Code chance of OneException" you know how to handle OneException, but not Exception, right? So then...only handle OneException.
Always catch exactly what you have to and no more. No matter how much we try, we cannot make our code completely "idiot proof". If someone passes you something which will cause some random error, then it is their job to handle it. If our code handles someone else's exception that has far too much risk of being an unexpected side-effect.
As far as what code to place where: code before the line which could throw the Exception will be run either way, so it does not really make sense to have it inside the try block and before the code which throws. Code after the potential exception should be placed between try and catch if and only if it depends on the exception generating code. So, if your database connection call can fail, place all of the database queries inside the try block.
Limiting the "time" spent in a try...catch makes it easier to read and less prone to accidental catching. I can't tell you how many hours have been lost because someone decided to catch an Exception which should have propagated.
a) It is bad practice, to place complete code inside a try block.
a1) Beside of catching exceptions, a try-block is a documentation where an exception might happen. So place it close to the cause, you have in mind.
a2) In bad circumstances, you have a file for reading, and add later one for writing, but your exception (FileNotFoundException) was written only with the first in mind. A lean scope around the problematic places will help you, identifying further problems.
b) Don't catch basic Exception for completeness or to avoid multiple catch blocks. If you want to write to a file, many things can go wrong: Missing permission, illegal file name, no space left on device, ... . If you present the user a generic Message ("Couldn't write file " + name), he doesn't know what to do. Be as specific as possible, and you can inform him, "Only 20 MB left on device " + devicename + "We need another 8 MB (28 MB in total); please free some space and repeat or choose a different device!"). If you catch "Exception", chances are high, that you're thinking of some exception, but another one occurs, and isn't handled correctly, because the catch-block wasn't written with that possibility in mind.
The best chance to find this exception is, to let it pop up, or, to log it, if the logs are controlled on a regular basis.
It can be a difference between developing an application, which is simply used by end users, or by developing an API, which is used by other developers.
In an API, you often want to wrap an exception into an own exception, to make it easier for users of your api to handle it, and if you have an uniform way to handle exceptions. If your code can throw many exceptions, and would lead to ugly client code, where your customer would need to specify a bunch of exceptions over and over again, you often wrap the exceptions and rethrow them:
try {
...
}
catch {FileNotFoundException fnfe}
{
throw new MyApiException (fnfe);
}
catch {PermissionDeniedException pde}
{
throw new MyApiException (pde);
}
catch {IOException ioe}
{
throw new MyApiException (ioe);
}
That way, your client can decide, how to handle the exception, and will find the specific type of exception, if interested, inside your exception.
As Landei points out, in Java 7 there will be a simplified technique, to catch multiple exceptions, but not only such with a common superclass, see this link here
Wrap the code at the point where you really can handle the exception, and where you can handle the error. If you can't handle the error in the function, then do no wrap the code in try/catch block.
I don't know for java, but in c++ you should catch by const reference :
try
{
// code that can throw an exception
}
catch ( const SomeExceptionType & error )
{
// handle the error
}
C++ isn't Java or C# or... where you need catch (or finally) clauses to clean up after yourself. In C++, RAII does that. Consequently, I rarely ever write try/catch statements in C++, to the point where I consider it a code smell.
So, rather than contemplating which style of code you should use in conjunction with try/catch, you should ask yourself whether you need that try/catch at all.
What is better coding practice: if I have to have a try/catch block shall I place everything (every initialization and so on) in this block or just those variables which may throw? Is there any difference between those two constructions?
In example:
Having:
struct A {
A();
int a;
int* b;
};
and later on in .cpp:
A::A() {
a = 5;
try {
b = new int;
}
catch(...){
}
}
or
A:A() {
try {
a = 5; //this time in try block
b = new int;
}
catch(...) {
}
}
is there any difference between those two constructs or is this in a way if I have to have a try/catch block I may aswell put everything in it?
Thank you.
P.S.
For God efin sake, formatting here drives me really crazy! And I know that I mentioned this many times, I'm not going mad.
I think a good general principle is to make a try block as "narrow" as possible -- don't put in it things that you believe won't ever cause exceptions. That way, should you ever be wrong and have one of those "can't cause exception" parts actually do cause an exception, you won't be accidentally "swallowing" the astonishing exception (and no doubt dealing with it in inappropriate ways, since your code would not be expecting that exception but other kinds).
In your code, I would not use a try block at the point you indicate at all. Memory allocation errors are actually both very rare and very difficult to recover from. I would probably catch the exception in main, log the error and exit the program.
More broadly, in C++ you should not wrap every function that could throw in a try block. You should instead write code that can cope with exceptions, using well-known C++ idioms like RAII.
In addition to the very good points by Alex and Neil, the narrow try block makes for an easier to understand code. A future maintainer will know more easily what's going on.
# Alex,
I disagree. You should group logical parts of your program into try catches that should fail or pass as a whole. If something fails, even if you didn't expect it your code should be exception safe and the whole operation should fail and all resources should automatically be released. If you make them narrow then you just end up with tons and tons of try's and catches. Why not just use IF's? (but wasn't that the point of exceptions in the first place? avoid tons of ifs?)
Parashift agrees with me too.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.12
read 17.12 and 17.13.
Another way to look at this is to include statements in a try block when they all need to succeed or fail together. This way, catch blocks act as a kind of transactional feature in your code. So, you can do something like:
// save current state
try {
// a few statements
// that each modify the state
} catch (e) {
// rollback to original state
}
In your example, assigning to member variable a changes the state of the object, so it should be inside the try block.
In my code, I rarely ever catch anything, except in main(). If you feel like you need catch blocks to clean up after yourself, you do something wrong and need to have a good look at the RAII idiom. As for anything else - an exception should be thrown under exceptional circumstances only, and it's very hard to come up with something generic and smart to do in exceptional moments.
Each time I have seen the catch all statement:
try
{
// some code
}
catch (...)
{
}
it has always been an abuse.
The arguments against using cache all clauses are obvious. It will catch anything including OS generated exceptions such as access violations.
Since the exception handler can't know what it's dealing with, in most cases the exceptions will manifest as obscure log messages or some incoherent message box.
So catch(...) seems inherently evil.
But it is still implemented in C++ and other languages (Java, C#) implements similar mechanisms. So is there some cases when its usage is justified?
(1) It's not true that the statement will catch OS exceptions. Your use of the term "Access Violation" betrays a Windows background; it was true for older MSVC++ versions.
(2) Regardsless, the catch-all behavior is useful for threads with specific purposes. Catching the failure allows the thread to report it failed. Without it, the other parts of the program need to deal with the possibility of a thread just disappearing. It also allows you to log which thread failed, and the arguments used to start the thread.
The case where it's justified in general is when you log the exception (or do something similar) or do some cleanup, and then immediately rethrow.
In C++ in particular, logging in a catch(...) block is pretty pointless since you don't have any way to obtain the exception, and cleanup is pointless because you should be using RAII for that. Using it in destructors seems to be about the only legitimate case.
the arguments against using cache all clauses are obvious , it will catch anything including OS generated exceptions such as access violation. since the exception handler can't know what its dealing with, in most cases the exceptions will manifest as obscure log message or some incoherent message box.
And if those same exceptions aren't caught you get... an incoherent message box.
catch(...) lets me at least present my own message box (and invoke custom logging, save a crash dump, etc.).
I think there are also reasonable uses of catch(...) in destructors. Destructors can't throw--well, I mean, they can throw, but if a destructor throws during stack unwinding due to an in-progress exception the program terminates, so they should not ever allow exceptions to escape. It is in general better to allow the first exception to continue to be unwound than to terminate the program.
Another situation is in a worker thread that can run arbitrary functions; generally you don't want an unceremonious crash if the task throws an exception. A catch(...) in the worker thread provides the opportunity for semi-orderly clean-up and shutdown.
In addition to what other posters have already said, I'd like to mention one nice point from the C++ Standard:
If no matching handler is found in a
program, the function std::terminate()
is called; whether or not the stack is
unwound before this call to
std::terminate() is
implementation-deļ¬ned.
(15.3/9)
This means that main() and every thread function must be wrapped in a catch-all handler; otherwise, one can't even be sure that destructors for automatic objects will be called if an uncaught exception is thrown.
try {...} catch (...) is needed around body of callback function which is called from code
that doesn't understand C++ exceptions (usually C library).
Otherwise, if some C++ library you use throws an exception that doesn't derive from
std::exception, it will probably cause calling code to crash or corrupt its internal state.
Instead you should catch this exception and either finish program immediately or
return some error code (meaning "we are doomed and I don't know why", but it's still better
then letting C++ exception to pass through).
Around thread procedure. Mostly because of the same reason as 1.
And because otherwise thread failure would pass unnoticed.
catch(...) has been useful for me in two circumstances, both of which are unjustified (I can't even remember the second)
The first is my overall application safety. While throwing exceptions that don't derive from std::exception is a No-No, I have one just in case in my main() function:
int execute(void); // real program lies here
int main(void)
{
try
{
return execute();
}
catch(const std::exception& e)
{
// or similar
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown exception!" << std::endl;
return EXIT_FAILURE;
}
}
Now, it's only there "just in case", and it's not really justified. There should be no reason to ever enter that catch clause, as that would mean somebody has done a Bad Thing. Observe how useless the statement really is; "Something bad happened, no clue what!" It's only a step above just crashing in the first place.
The second use might be in destructors or some other function that needs to do manual management before letting the exception propagate. That's not really a justification either, as things should clean themselves up safely with RAII. But I may have used it once or twice for some reason I can't recall, and I can't see a reason to ever do so again.
catch (...) allows you to write code in which you can legitimately claim a guarantee that your code will not crash even when you are not in long term complete control of the submodules your code depends on. Your claim is tantamount to claiming that this semantic cannot be used except as a means of abuse. Maybe so, but military specifications may differ from you on this issue.
catch(...) is necessary in the absence of the finally clause as found in other languages:
try {
...
} catch(...) {
cleanup...
throw;
}
The alternative - making stack objects to 'own' everything - is often much more code and less readable and maintainable. The platform API is often C, and does not come with it conveniently bundled.
It is also useful around plugin code that you do not control or simply do not trust from a stability perspective. It won't stop them crashing, but it might keep things a little saner.
Finally, there are times when you really do not care about the outcome of something.