#if 0
int func()
{
//...
FILE* pfile;
if (!(pfile = fopen("null", "r")))
{
//...
cout << "文件打开失败" << endl;
return -1;
}
return 0;
}
int func2()
{
if (-1 == func())
{
//错误处理
}
}
int main()//缺点 逐层判断 优点 层次清晰
{
if (-1 == func2())
{
//...返回值带错误
}
return 0;
}
#endif//利用返回值
#if 0
#include<setjmp.h>
jmp_buf j_err;
void func3()
{
//...
FILE* pFile;
if (!(pFile = fopen("null", "r")))
{
//...
cout << "调用longjmp前" << endl;
longjmp(j_err, -1);
cout << "调用longkmp后" << endl;
}
}
void func4()
{
cout << "调用func3前" << endl;
func3();
cout << "调用func3后" << endl;
}
int main()
{
if (setjmp(j_err) == 0)//j_err默认0
{
cout << "第一次调用setjmp" << endl;
func4();
}
else
{
cout << "第二次调用setjmp" << endl;
}
return 0;
}
#endif // setjmp longjmp
#if 0
void func()
{
FILE* pFile;
if (!(pFile = fopen("null","r")))
{
//...
throw - 1;
}
char* p = (char*)malloc(0x123213);
if(!p)
{
throw "内存分配失败";
}
}
int main()
{
try
{
func();
}
catch (int ex)
{
if (-1 == ex)
{
cout << "文件打开失败\n";
return -1;
}
}
catch (const char* ex)
{
cout << ex<< endl;
}
return 0;
}
#endif // 抛出 捕获异常
#if 0
class A
{};
class :public A
{};
int main()
{
try
{
throw B();//抛出B类型异常
}
catch (A& ex) //被A捕获 根据异常类型从上到下匹配 而非优先匹配
//因此对子类类型异常的捕获不要放在对基类类型异常捕获的后面
{
cout << "A异常" << endl;
}
catch (B& ex)//用引用来接 ex就是异常 不用就是异常的拷贝
{
cout << "B异常" << endl;
}
return 0;
}
#endif//捕获顺序
#if 0
class OverFlow :public exception
{
//...
const char* what()const throw()
{
return "堆栈饱满";
}
};
void push(int data)
{
//...
//throw overflow_error("堆栈上溢");
throw OverFlow();
}
int main()
{
try
{
push(10);
}
catch (exception& ex)//异常的基类 exception
{
cout << ex.what() << endl;
}
return 0;
}
#endif // 标准异常库