主程序的异常处理结构
下面这段程序,实现了一个良好的main()函数结构。我这里解释一下他的功能和实现方法。
1、它处理整个程序的异常。整体框架被包括在一个try/catch结构里面。
2、它通过一个计数器restart,标记了之前运行得出错误数。这样在yourMain(int restart)中,就可以根据restart来判断这是第几次重新启动,并且可以做一些之前的异常情况的处理。
3、通过一个while来不断尝试重新开始程序。并通过标志位running来决定是否继续执行。
4、这里要注意几个问题,首先如果每次调用yourMain都会产生一个异常,这个结构就进入了死循环。你需要手动检查这是第几次运行,如果次数累计到一定程度,应该强制终止。
5、在捕获到异常,并重新调用yourMain的时候,全局或静态变量不会重新初始化。必须显式的重新初始化。
[code:c]
int yourMain(int restart)
{
// Your main function goes here.
}
int primaryMain()
{
int retval = 0;
bool running = true;
int restart = 0; // restart count
while(running)
{
try {
// Run the application
retval = yourMain(restart);
if (retval == 0) then running = false;
}
catch (std::exception& ex) {
// TODO: some error info ouput here.
restart++;
// Add code to decide if we should fail instead of restarting
}
catch(...) {
// TODO: some error info ouput here.
retval = 1;
running = false;
}
}
return retval;
}
int catchMain()
{
try {
// Run the application
return primaryMain();
}
catch(...) {
// TODO: some error info ouput here.
return 1;
}
return catchMain();
}
int main()
{
// TODO: set up something you need, like debug stream
return catchMain();
}[/code]
留下 您的足印