C++异常处理
语法应用
bool fun()
{
int a = 7, b = 0;
//if (b == 0) throw "error!";
if (b == 0) throw 404.1;
int c = a / b;
}
int main(int argc, const char** argv)
{
try
{
fun();
}
catch(int e){
cout << e << endl;
}
catch (const char *error)
{
cout << error << endl;
}
catch (...) {
cout << "捕获任何异常,通用性强但是匹配性差" << endl;
}
return 0;
}
处理除零异常
#include<iostream>
using namespace std;
int divide(int x, int y) {
if (y == 0){
throw x;
}
return x / y;
}
int main()
{
try{
cout << " divide(1, 2):\t" << divide(1, 2) << endl;
cout << " divide(2, 0):\t" << divide(2, 0) << endl;
cout << " divide(4, 2):\t" << divide(4, 2) << endl;
}catch (int e){
cout << e << " divide is zero" << endl;
}
cout << "That's OK!";
return 0;
}
异常接口说明
void fun() throw(A, B, C, D)
在函数声明中列出可能抛掷的所有异常类型- 若不抛出任何异常
void fun() throw()
void fun()
可以抛掷任何异常
异常类的例子
C++异常处理真正功能在于为异常抛掷前构造的所有局部对象自动调用析构函数
#include<iostream>
#include<string>
using namespace std;
class myException
{
public:
myException(const string& message) :m_message(message) {}
myException() {}
const string& getMessage() const {
return m_message;
}
private:
string m_message;
};
class Demo
{
public:
Demo() {
cout << "Constructor of Demo" << endl;
}
~Demo(){
cout << "Destructor of Demo" << endl;
}
};
void func() throw (myException) {
Demo d;
cout << "Throw myException in func()" << endl;
throw myException("exception thrown by func()");
}
int main()
{
cout << "in main thread" << endl;
try{
func();
}catch (myException& e){
cout << "caught an exception: " << e.getMessage() << endl;
}
cout << "see you!";
return 0;
}