Reputation: 1360
I mean, I knew all the language rules about throw, try {} catch {}, but I am not sure if I am using them correctly in the real world. Please see the following example:
We have a large piece of scientific code which did all sorts of image processing things, recently we decided to spruce it up and make it more robust. One of the routines which is frequently used is void rotate_in_place(float* image, image_size sz);
To make it more robust, we add some sanity check at the beginning of the code:
void rotate_in_place(float* image, image_size sz) {
// rotate_in_place does not support non-square image;
if (sz.nx != sz.ny) throw NonSquareImageError;
// rotate_in_place does not support image too small or too large
if (sz.nx <= 2 || sz.nx > 1024) throw WrongImageSizeError;
// Real rode here
.....
}
Now the problem is that rotate_in_place() is used in over 1000 places, shall I wrap each call of rotate_in_place() with try{} catch {}, this looks to me will make code incredibly bloated. Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using
if (sz.nx != sz.ny) {
cerr << "Error: non-squared image error!\n";
exit(0);
}
In short, I am not so sure about the real benefit of using throw, try, catch, any good suggestions?
Upvotes: 6
Views: 1274
Reputation: 106530
The general rule for exceptions is, "Does the immediate call site care about what's going on here?" If the call site does care, then returning a status code probably makes sense. Otherwise, throwing makes more sense.
Consider it this way -- sure, your rotate in place method has a couple of invalid argument types, in which case you should probably throw std::invalid_argument
. It's unlikely that a caller of rotate_in_place
wants to deal with or knows how to deal with the case that an image was not square, for example, and therefore that's probably better expressed as an exception.
Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using
if (sz.nx != sz.ny) { cerr << "Error: non-squared image error!\n"; exit(0); }
It's different because if someone later wants to take your function and put it in, say, a GUI application, they don't have to terminate the program based on the error. They can turn that exception into something pretty for the user or something like that.
It also has benefits for you right now -- namely that you don't have to pull <iostream>
into that translation unit simply to do error writing.
I usually use a pattern something like this:
int realEntryPoint()
{
//Program goes here
}
int main()
{
//Allow the debugger to get the exception if this is a debug binary
#ifdef NDEBUG
try
#endif
{
return realEntryPoint();
}
#ifdef NDEBUG
catch (std::exception& ex)
{
std::cerr << "An exception was thrown: " << ex.what() << std::endl;
}
#endif
}
Upvotes: 5
Reputation: 129774
Every site that handles the error needs try
-catch
block. It all depends on your design, but I doubt you need to handle the error in every rotate_in_place
call-site, you probably get away from propagating upwards most of the time.
Printing the error and using exit
is bad for three reasons:
exit
is not handling (unless it's done when the error is absolutely critical, but your function cannot know that — caller might have a way to recover).rotate_in_place
, not rotate_in_place_and_print_errors_and_kill_the_program_if_something_is_wrong
) — this hurts reusability.Upvotes: 6
Reputation: 56956
The point in using exception handling holds in following simple rules:
The thing to remember is: The exception should bubble up to the point where it can be handled. This can mean a dialog box with some formatting of the error, or this can imply that some unimportant piece of logic won't be executed after all, etc.
Upvotes: 3
Reputation: 375
Well, I agree that really using Exceptions results in bloated code. That is the main reason for me not liking them.
Anyway, as to your example: The key difference between throwing exceptions and just using exit() is that, since the handling of the exception happens (or is supposed to happen) outside of the program fragment that generated the error/exception, you do not specify how the user of a function/class has to handle the error. By using exceptions you allow different treatments like aborting the program, reporting errors or even recovering from certain errors.
TLDNR: If you use exceptions, the exception-generating part of the code does not need to specify how the exceptional case is treated. That happens in the outside program and can be changed depending on how the code is being used.
Upvotes: 0
Reputation: 19790
What you can do is to make rotate_in_place return a boolean if the function call was succesfull. And return the rotated image via a function parameter.
bool rotate_in_place(float* image, image_size sz, float** rotated_image) {
// rotate_in_place does not support non-square image;
if (sz.nx != sz.ny) return false;
// rotate_in_place does not support image too small or too large
if (sz.nx <= 2 || sz.nx > 1024) return false;
// Real rode here
.....
return true;
}
Upvotes: 1
Reputation: 363547
Now the problem is that rotate_in_place() is used in over 1000 places, shall I wrap each call of
rotate_in_place()
withtry{} catch {}
, this looks to me will make code incredibly bloated.
It will, and it beats the purpose of using exceptions in the first place.
Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using [...]
That you can always change the location of exception handling later on. If at some point you find a better place to sensibly handle the error (perhaps recovering from it), then that's the point where you put the catch
. Sometimes that's in the very function where you throw the exception; sometimes it's way up in the call chain.
Do put a catch
-all in main
, just in case. Deriving exceptions from standard ones such as std::runtime_error
makes doing this a lot easier.
Upvotes: 4
Reputation: 3012
It depends.
Exceptions are generally meant to be caught/handled. In your case, is it possible to handle the exception (for instance, the user provides a non-square image, so you ask them to try again). However if there is nothing you can do about it, then cerr
is the way to go.
Upvotes: 0
Reputation: 223003
Using exceptions allows the caller to decide how to handle an error. If you called exit
directly within the function, then the program would exit without the caller being able to decide how to handle the error. Also, with exit
, stack objects would not be unwound. :-(
Upvotes: 1