假设错误处理
现在你知道假设错误通常发生,让我们完成了在不同的方式处理他们当他们出现。没有最好的方式来处理一个错误-这真的取决于问题的性质。
这里有一些典型的反应:
1)悄悄地跳过代码依赖于假设是有效的:
1
2
3
4
5
6
void PrintString(char *strString)
{
// Only print if strString is non-null
if (strString)
std::cout << strString;
在上面的例子中,如果strstring是空的,我们不打印任何东西。我们必须跳过的代码依赖于strstring非空。
2)如果我们是一个函数,返回一个错误代码返回给调用者,让来电者处理问题。
1
2
3
4
5
6
7
8
9
10
int g_anArray[10]; // a global array of 10 characters
int GetArrayValue(int nIndex)
{
// use if statement to detect violated assumption
if (nIndex < 0 || nIndex > 9)
return -1; // return error code to caller
return g_anArray[nIndex];
}
在这种情况下,函数返回1,如果用户通过无效索引。
3)如果我们想终止程序立即退出函数,可以返回一个错误代码的操作系统:
2
3
4
5
6
7
8
9
10
int g_anArray[10]; // a global array of 10 characters
int GetArrayValue(int nIndex)
{
// use if statement to detect violated assumption
if (nIndex < 0 || nIndex > 9)
exit(2); // terminate program and return error number 2 to OS
return g_anArray[nIndex];
}