在原始代碼中缺少恢復(fù)或日志記錄的功能,如果發(fā)生了一個錯誤,程序就會"消失"不見了,讓用戶手足無措。下面是重新組織后的代碼,注意,沒有修改函數(shù)修飾符:
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:
//記錄錯誤信息
...
//試圖恢復(fù)
...
if ( recovered ) {
continue;
} else {
throw(E_IRRECOVERABLE);
}
break;
case ...
}
}
//繼續(xù)處理
...
}
//throw()可以用來取代缺少的返回碼
//但也要注意由此帶來的性能損失
throw(S_OK);
} // ProcessMail()
void ReadMail(...)
{
...
//在此無須捕捉異常
nBytesAvailable = ReadBytes(...)
...
}
int ReadBytes(...)
{
//讀取數(shù)據(jù)
if ( error ) {
throw(E_READ_ERROR);
}
return nBytesRead;
}
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:
//記錄錯誤信息
...
//試圖恢復(fù)
...
if ( recovered ) {
continue;
} else {
throw(E_IRRECOVERABLE);
}
break;
case ...
}
}
//繼續(xù)處理
...
}
//throw()可以用來取代缺少的返回碼
//但也要注意由此帶來的性能損失
throw(S_OK);
} // ProcessMail()
void ReadMail(...)
{
...
//在此無須捕捉異常
nBytesAvailable = ReadBytes(...)
...
}
int ReadBytes(...)
{
//讀取數(shù)據(jù)
if ( error ) {
throw(E_READ_ERROR);
}
return nBytesRead;
}

