可获得抛出异常位置和捕获异常位置的异常类
联系方法:dyj057@gmail.com
源代码:http://www.cnblogs.com/Files/dyj057/typeId.rar
我觉得C++中使用异常在使用中最大的不方便就是在抛出异常的时候没有位置信息,当程序到一定规模的时候,也很难确定异常从那里捕获的,不利于程序的调试。而在C#中,我发现它的异常的功能太强大了,可以确定异常的位置和捕获的位置,但它是靠CLR的功能实现的。那么我们怎么在C++中实现这个功能呢?
下面我就为大家介绍我写的可以获得抛出异常位置和捕获异常位置的异常类。该类使用标准C++实现,继承标准异常exception。你也可以按照这个思路实现一个MFC的版本。我在使用的时候就是使用两个不同的版本。MFC的版本的功能要强大一点,它内置了Win32错误代码转换错误信息的转换函数,为程序提供更强大的异常处理功能。
现在来看看类的定义:
class more_exception :
public exception
{
public:
more_exception(string what, string throw_file,
string throw_function, int throw_line) ;
more_exception(const more_exception& right);
more_exception& operator=(const more_exception& right);
virtual ~more_exception(void) ;
virtual const char *what( ) const;
//throw exception position
const char *get_throw_file() const ;
const char *get_throw_function() const ;
int get_throw_line() const ;
//set catch exception position
void set_catch_file(const char *catch_file);
void set_catch_function(const char *catch_function);
void set_catch_line(int catch_line);
//get catch exception position
const char *get_catch_file() const ;
const char *get_catch_function() const ;
int get_catch_line() const ;
private:
string m_what;
string m_throw_file;
string m_throw_function;
int m_throw_line;
string m_catch_file;
string m_catch_function;
int m_catch_line;
};
定义非常的简单,没有什么技巧可言,很容易懂。最重要的是使用了两个宏获得抛出异常位置的信息和捕获异常的位置信息。
l 获得抛出异常的位置信息
#define THROWEXCEPTION(what) more_exception ex(what, __FILE__, __FUNCTION__, __LINE__); throw ex;
当你需要抛出异常的时候,使用这个宏替代一般的方法。
比如:使用THROWEXCEPTION(“There is a exception”) 来代替throw ex(“There is a exception”),这样就可以可以获得方便的获得异常的抛出的位置,当然你可以自己执行宏里面的方法。
捕获异常的时候一定要使用引用来捕获异常,至于为什么,请看《More Effective C++》的异常部分。
l 获得捕获异常的位置信息
#define SETCATCHEXCEPTIONPOS(more_ex)more_ex.set_catch_file(__FILE__);more_ex.set_catch_function( __FUNCTION__ ); more_ex.set_catch_line(__LINE__);
这个宏也很简单是用来为捕获到异常添加捕获异常的位置信息的。使用方法:
try
{
…
}
catch(more_exception &e)
{
SETCATCHEXCEPTIONPOS(e);
print(e);
}
与C#中的异常类比较,它少了异常扩散的路径,甚是遗憾。
注意:源程序在Windows XP professional + SP2, Visual .NET 2003 环境下编译通过。