1-异常基本语法.cpp
#include <iostream>
using namespace std;
int Div(int x, int y)
{
if (0 == y)
{
//return -1;
//throw 0; //抛出异常
throw 'a';
}
return x / y;
}
int main()
{
int a, b;
cin >> a >> b;
try{ //把可能抛出异常的代码放在try语句中
cout << Div(a, b) << endl;
}
catch(int)
{
cout << "zero exception" << endl;
}
catch (char)
{
cout << "char exception" << endl;
}
return 0;
}
2-异常的思想.cpp
#include <iostream>
using namespace std;
int DDiv(int x, int y)
{
if (0 == y)
{
throw 0;
}
return x / y;
}
int Div(int x, int y)
{
/*int ret = DDiv(x, y);
if (0 == ret)
{
}
else
{
}*/
return DDiv(x, y);
}
int main()
{
int a, b;
cin >> a >> b;
try{ //把可能抛出异常的代码放在try语句中
cout << Div(a, b) << endl;
}
catch(int)
{
cout << "zero exception" << endl;
}
catch (char)
{
cout << "char exception" << endl;
}
return 0;
}
3-异常声明.cpp
#include <iostream>
using namespace std;
int Div(int x, int y) throw(int, char); //只能抛出整形或者字符型异常
//int Div(int x, int y) throw(); //不会抛出任何类型异常
//int Div(int x, int y); //可能抛出任何类型的异常
int main()
{
int a, b;
cin >> a >> b;
try{ //把可能抛出异常的代码放在try语句中
cout << Div(a, b) << endl;
}
catch(int)
{
cout << "zero exception" << endl;
}
catch (char)
{
cout << "char exception" << endl;
}
return 0;
}
int Div(int x, int y) throw(int, char)
{
if (0 == y)
{
//return -1;
//throw 0; //抛出异常
throw 'a';
}
return x / y;
}
4-异常对象.cpp
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test构造函数" << endl;
}
Test(const Test &t)
{
cout << "Test拷贝构造函数" << endl;
}
void print()
{
cout << "Test Exceotion" << endl;
}
~Test()
{
cout << "Test析构函数" << endl;
}
};
int Div(int x, int y)
{
if (0 == y)
{
throw Test(); //抛出对象
//throw new Test; //抛出对象指针
}
return x / y;
}
int main()
{
int a, b;
cin >> a >> b;
try{ //把可能抛出异常的代码放在try语句中
cout << Div(a, b) << endl;
}
catch(int)
{
cout << "zero exception" << endl;
}
catch (char)
{
cout << "char exception" << endl;
}
/*catch (Test t) //调用拷贝构造函数
{
t.print();
}*/
catch (Test &t) //推荐
{
t.print();
}
catch (Test *t)
{
t->print();
delete t; //需要手动释放
}
return 0;
}
5-标准异常库.cpp
#include <iostream>
#include <exception>
using namespace std;
int main()
{
try{
int *p = new int[-1];
}
catch (exception &e)
{
cout << e.what() << endl;
}
return 0;
}