您的位置:首页 > 编程语言 > C语言/C++

(C++)使用自定义的异常类获取源代码信息

2013-01-06 18:24 477 查看
如果在项目中使用异常机制,我们一般会定义一个类继承自std::exception,在throw时附带上自定义的信息。但是有时我们还希望知道某个异常是从何处抛出的,也就是源代码的文件,函数,行号信息。于是就写了这个ExceptionEx类,继承该类就能够很容易地获取上述信息。ExceptionEx的实现在这里:ExceptionEx

用法如下:

#include <iostream>
#include "ExceptionEx.h"

class MyException : public YaoUtil::ExceptionEx  
{  
public:  
    MyException(const std::string& what,  
        const std::string& file,  
        const std::string& func,  
        int line) : YaoUtil::ExceptionEx(what, file, func, line)  
    {  
    }  
};  

int main()
{
    try
    {
        // 抛出异常,使用宏代替throw关键字  
        THROW_EX(MyException, "just test");
    } 
    catch (MyException& me)  
    {  
        std::string info = me.GetInfo();  
        std::cout<<info<<std::endl;
    }
    std::cin.get();
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: