I have seen programs using this strategy and I have also seen posts considering this bad practice. However, the posts considering this bad practice have been written in c# or some other programming language, where there are some error handling built in. This question is about the c++. Further, the errors I am addressing are errors which are fatal enough to force a program to shutdown, not some general "maybe-I-have-missed-something-error". With using expressions at highest level I mean this in a bit sloppy sense. It can be either something like
int main(){
try {
//run
} catch (fatalException){
//handle error and shutdown
}
}
or it can be something like this in for example a graphical application.
void runApplication(){
try {
//run
} catch (fatalException){
//handle error and shutdown
}
}
The alternative to this would be to handle this error where it happens and hierarchically return from functions, one-by-one until the program is terminated. The reason I can see for terminating fatal errors by a try-catch on the top level is that the reasons for this kind of error can be different, and is probably fairly unusual (corrupted databases, some out-of-memory errors, corrupted configuration files, etc...). Handling exceptions locally and return from functions one-by-one would make the code less clear and require much effort to handle problems which are unlikely to occur.
However, I am not sure whether it is good practice to start the program with a try
. Personally, I think it is ugly, but somehow this ugliness reflects the ugliness of the problem itself, so this may not be a reason to not use it for this case.
EDIT I may have misunderstood the dupe post, but I do not think this solves the problem. The question is not about not-catching some exceptions. The point is that there is in most cases are other parts of the code which can handle the exception closer the the throw in a fairly satisfactory way, but to the cost of having to step through the hierarchy to the top and terminate. However, since the program would still need termination, are there in general any reason to catch earlier that on top level? One can argue that this implies that the lower levels are unable to decide how to handle this. But in this case I believe it is unclear. I mean "what error would have the authority to determine if a program needs to terminate?"