c++ 异常处理设计到三个关键字,分别是throw,try和catch。
程序使用throw抛出异常,将可能出错的程序段放在try中,并用catch进行捕获。
先举个例子:
<pre name="code" class="cpp">#include <iostream>
#include <string>
using namespace std;
void test()
{
throw "exception";
cout<<"test()"<<endl;
}
int main()
{
try{
test();
}
catch(const char *str)
{
cout<<str<<endl;
}
}
程序将输出:
exception
如上程序,将可能抛出异常的test程序放入try语句块中,然后执行到test中,抛出异常,使用catch捕获,将异常输出。注意当test中异常发生后,test程序段后面的程序部分将不会输出,也就是程序中的test()语句。
当然,一般我们在程序中可能会多加几个catch,使得捕获的异常的类型更多。
一般关于普通的异常就是这样,但是我们写程序有可能会将异常和c++多态结合起来,这样异常就显得高大上了。
<pre name="code" class="cpp">#include <iostream>
using namespace std;
class Exception{
public:
virtual void printException()
{
cout<<"Exception printException()"<<endl;
}
virtual ~Exception(){}
};
class IndexException : public Exception
{
virtual void printException()
{
cout<<"Index Exception printException()"<<endl;
}
virtual ~IndexException(){}
};
void test()
{
throw IndexException();
}
int main()
{
try{
test();
}
catch(const Exception &e)
{
e.printException();
}
}
输出:
Index Exception printException()
这样我们可以定义一个接口类,作为一个异常处理的基类,然后在用各种继承类继承接口类,在异常处理捕获的时候只需用基类的类,这样依据多态特性,程序自然能正确处理传入异常的实际的参数。