一、异常处理
在c++中,异常处理使用throw抛出异常,try…catch执行异常处理内容。
例如,在进行除法运算时,除数不能为0,我们可以采用返回一个标识数字判断计算异常,如-1,0等,但这样就会存在与某些结果产生歧义,比如运算结果就-1,或者0.这还只是简单的情况,对于复杂的程序,其异常有很多种,那么,异常处理则是必然需要的。
设计异常抛出时,throw可能出现异常的数据,编写相应异常提示语句
#include<iostream>
#include<string>
using namespace std;
template<class T>
T mydiv(T a, T b)
{
if (!b)
throw b;
return a / b;
}
template<class T>
void test()
{
T a, b;
cin >> a >> b;
try {
cout << "res=" << mydiv<T>(10.0, 0) << endl;
}
catch (int e) {
cout << "int类型异常 " << e << endl;
}
catch (float e) {
cout << "float类型异常 " << e << endl;
}
catch (double e) {
cout << "double类型异常 " << e << endl;
}
}
int main()
{
cout << "请输入两int类型变量:" << endl;
test<int>();
cout << "请输入两float类型变量:" << endl;
test<float>();
cout << "请输入两double类型变量:" << endl;
test<double>();
return 0;
}
如此,便将程序中所存在的异常清晰的指了出来,且不影响后续程序执行。
二、栈解旋
#include<iostream>
#include<string>
using namespace std;
class Person
{
string name;
public:
Person(string name) :name(name) { cout <<name<<"的构造函数" << endl; }
~Person(){cout<<name<<"的析构函数"<<endl; }
};
int main()
{
try {
Person p1("hhh");
Person p2("aaa");
Person p3("eee");
throw 10;
}
catch (int)
{
cout << "int类型异常" << endl;
}
return 0;
}
从try块起至异常被抛出前,期间创建在栈上的对象会自动析构且与构造顺序相反,因此称其为栈解旋。
三、异常规范(C++11已弃用)
#include<iostream>
#include<string>
using namespace std;
void Throwtest() throw()
{
//throw "hh";
throw 123;
}
int main()
{
try {
Throwtest();
}
catch(int e)
{
cout << "int类型异常 "<<e << endl;
}
catch (string e)
{
cout << "string类型异常" << e << endl;
}
catch (char e)
{
cout << "char类型异常" << e << endl;
}
}
四、异常的生命周期
#include<iostream>
#include<string>
using namespace std;
class MyException
{
public:
MyException() { cout << "异常的构造函数" << endl; }
~MyException() { cout << "异常的析构函数" << endl; }
};
int main()
{
try {
throw new MyException;
}
catch(MyException e)
{
cout << "捕获到MyExpection异常 "<<endl;
}
catch (MyException&e)
{
cout << "捕获到MyExpection&异常 " << endl;
}
catch (MyException*e)
{
cout << "捕获到MyException*异常" << endl;
delete e;//注意释放
}
}
五、 异常的多态使用
#include<iostream>
using namespace std;
class BaseException {
public:
virtual void printError() {};
};
class NULLPointerError:public BaseException
{
public:
virtual void printError() {
cout << "空指针异常!" << endl;
}
};
int main()
{
try {
throw NULLPointerError();
}
catch (BaseException&ex) {
ex.printError();
}
}
六、cin的部分使用
#include<iostream>
using namespace std;
int main()
{
char res;
res=cin.get();
cout << res<<endl;
cin.putback(res);
cout << "偷窥缓冲区的数据" << cin.peek() << endl;
cout<<"忽略两字节偷窥 "<<cin.ignore(2).peek()<<endl;
}