Code for Unintentional Failure

Possible duplicate:
What is the easiest way to make a C ++ program crash?

There is a construction that I often see in our code base, where the program somehow gets into an invalid state, the code will do something intentionally wrong, just to cause a crash. This usually happens like this:

if(<something is wrong>) { int *ptr = NULL; *ptr = 0; } 

This of course leads to a null reference exception and the program crashes in an unrecoverable manner. I'm just wondering if this is really the best way to do this? First of all, it is poorly read. Without comment, you may not understand that an accident occurred here. Secondly, it is almost impossible to restore it. It does not throw an exception, so it cannot be handled by other code. It just kills the program dead without the possibility of a return. It also does not provide much information on why he should have crashed here. And this will happen in all assemblies, in contrast to, say, the statement. (We have a fairly robust claim system, but it is not always used in such cases.)

This is a style that we use everywhere, and I am not able to try to convince anyone else. I just wonder how this is common in the industry.

+4
source share
3 answers

You should throw an exception that basically causes a deliberate and controlled drop. Here is an example using this question .

 throw string("something_went_wrong"); 

Even better, the error is caught or fixed. Approval would also be a good choice.

+2
source

You cannot β€œcrash” a program intentionally, because by its very definition, an accident occurs when the program goes wrong and does not behave deterministically.

The standard way to complete execution is through std::terminate ; The usual way to achieve this is to call std::abort , which causes a non-blocking signal to the process (automatically leads to std::terminate ), and also causes many operating systems to dump the kernel.

+3
source

I assume this is a way to start a core dump in situations where you are not debugging. Then a kernel dump gives you enough information to analyze the problem. In the case of "programmer errors" (or errors), this is better than throwing an exception, because stack promotion will not allow you to build a reasonable core dump. A similar effect can be achieved in a more elegant way by calling std :: terminate, after registering (using std :: set_terminate) a function that generates a kernel dump or something similar. See this article for more details.

+1
source

Source: https://habr.com/ru/post/1447600/


All Articles