从C++的异常处理机制我们可以知道,可以抛出不同类型的异常,不同类型的异常由不同的catch 语句负责处理。
那么,C++中的自定义类型也使用于异常机制吗?
示例代码:类类型的异常
#include <iostream>
#include <string>
using namespace std;
class Base
{
};
class Exception : public Base
{
int m_id;
string m_desc;
public:
Exception(int id, string desc)
{
m_id = id;
m_desc = desc;
}
int id() const
{
return m_id;
}
string description() const
{
return m_desc;
}
};
void func(int i)
{
if( i < 0 )
{
throw -1;
}
if( i > 100 )
{
throw -2;
}
if( i == 11 )
{
throw -3;
}
cout << "Run func..." << endl;
}
void MyFunc(int i)
{
try
{
func(i);
}
catch(int i)
{
switch(i)
{
case -1:
throw Exception(-1, "Invalid Parameter");
break;
case -2:
throw Exception(-2, "Runtime Exception");
break;
case -3:
throw Exception(-3, "Timeout Exception");
break;
}
}
}
int main(int argc, char *argv[])
{
try
{
MyFunc(11);
}
catch(const Exception& e)
{
cout << "Exception Info: " << endl;
cout << " ID: " << e.id() << endl;
cout << " Description: " << e.description() << endl;
}
catch(const Base& e)
{
cout << "catch(const Base& e)" << endl;
}
return 0;
}
分析:
1. 从代码来看:异常的类型可以是自定义类类型
2. 对于类类型异常的匹配依旧是至上而下严格匹配
3. 赋值兼容性原则在异常匹配中依然适用
a) 匹配子类异常的catch放在上部
b) 匹配父类异常的catch放在下部
4. 在定义catch语句块时推荐使用引用作为参数。
问题:为什么需要自定义类类型作为异常呢?在实际工程中是如何使用的?
在工程中常常会定义一系列的异常类,每个类代表功能中可能出现的一种异常类型。当代码复用时可能需要重新解释不同的异常类。
而C++中标准库中也提供了使用异常类族,标准库中的异常都是从EXCEPTION类派生的。有两个主要的分支
1. logic_error:常用语程序中的可避免逻辑错误
2. runtime_error:常用于程序中无法避免的恶性错误