在原始代码中缺少恢复或日志记录的功能,假如发生了一个错误,程序就会"消失"不见了,让用户手足无措。下面是重新组织后的代码,注重,没有修改函数修饰符:
void main() {
//初始化
...
try {
ProcessMail(...);
} catch (int ret) {
switch (ret) {
case E_INITIALIZATION_FAILURE: ...
case E_IRRECOVERABLE: ...
...
}
}
}
void ProcessMail(...) {
//初始化
...
if ( initializationError ) {
throw(E_INITIALIZATION_FAILURE);
}
while ( !shutdown ) {
try {
ReadMail(...)
} catch (int ret) {
switch (ret) {
case E_READ_ERROR:
//记录错误信息
...
//试图恢复
...
if ( recovered ) {
continue;
} else {
throw(E_IRRECOVERABLE);
}
break;
case ...
}
}
//继续处理
...
}
//throw()可以用来取代缺少的返回码
//但也要注重由此带来的性能损失
throw(S_OK);
} // ProcessMail()
void ReadMail(...)
{
...
//在此无须捕捉异常
nBytesAvailable = ReadBytes(...)
...
}
int ReadBytes(...)
{
//读取数据
if ( error ) {
throw(E_READ_ERROR);
}
return nBytesRead;
}
现在,修改以前遗留的老式项目时,是不是多点信心了呢?进入讨论组讨论。