Using try - catch for debugging

So, you wrote the program, launched it in the debugger - everything is fine, everything is fine. Put in the workflow - falls. Moreover, in the most unexpected places.
What to do?
Start to think. Put try-catch everywhere ... the computing unit will be great to slow down. So, you need to make a debug version. So, enter
#define __TRY__DEBUG__

Ok. Good. In suspicious places we put
#ifdef __TRY__DEBUG__ 
try{
#endif
//тело функции
#ifdef __TRY__DEBUG__ 
catch(...){
   fprintf(stderr,"Возникло исключение в функции %s. Сохраняю параметры\n",NameFunction);
   throw;
}
#endif

Oops the output function is scattered in different places. Not good.

An exception
class is born class DebugException: exception {}
Oops number two. And what to store in it?
So, do we need what? output to a file. It is desirable everything with which the function works at the time of the crash.
Those. we need text data.
Yeah.
struct Obj{
		//! имя
		char* name;
		//! состояние
		char* State;
		//! объекты
		Obj** MyObj;
		//! количество объектов
		int numberOfObjects;
		//! конструктор
		Obj(char*nm,char* stt):name(nm),State(stt),MyObj(NULL),namberOfObjects(0){	};
	};

So, let's move on. What to store, we’ve come up with, we’re thinking how to get this whole thing out of the object we are working with.
The Obj * GetState () method is born; which is registered in each class.
We are going further.
Now the question is: where to output something to a file?
You can in the same place where the crash. Those. in the exception constructor ... Yeah, not good.
The printf method appears in the exception class, which outputs the entire object to a file.
main begins to take the form
#ifdef __TRY__DEBUG__ 
try{
#endif
//тело функции
#ifdef __TRY__DEBUG__ 
catch(DebugException ups){
   ups.print();
   throw;
}
#endif

So, and it would be nice to collect information about the system as a whole. This is how a view constructor is born
	//! конструктор с  именем функции, необходимой информацией и состоянием функции
	DebugException(char*NmFunc,char GetStates,Obj* FuncState);


As a result, the code is doubled, but in case of a crash, you can find out who is the cause, who is the fault.

Pluses
+ much less summary information than with logging. Especially if the test version worked fine for two days, and the third one crashed.
+ It is possible to collect absolutely complete information about the system at the time of the crash.
+ Does not affect the release version.

Cons
- A completely different organization of function code. Since the variables declared in the try block are unknown in the catch block, they must be declared at the beginning of the functions, forgetting about the elegance of the code.
- A lot of debugging code
- Perhaps the reason that led to this state of the system will be lost

Also popular now: